-
Notifications
You must be signed in to change notification settings - Fork 35
/
zigzagconversion.java
33 lines (30 loc) · 1000 Bytes
/
zigzagconversion.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public String convert(String s, int numRows) {
//Define StringBuilders
StringBuilder[] sbs = new StringBuilder[numRows];
for(int i = 0; i < numRows; i++){
sbs[i] = new StringBuilder();
}
//Define Variables
char[] arr = s.toCharArray();
int n = arr.length;
int index = 0;
//Traverse zig zag
while(index < n){
//Go down
for(int j = 0; j < numRows && index < n; j++){
sbs[j].append(arr[index++]);
}
//Go Up before start
for(int j = numRows - 2; j > 0 && index < n; j--){
sbs[j].append(arr[index++]);
}
}
//Combine all stringbuilders into one
StringBuilder res = sbs[0];
for(int i = 1; i < numRows; i++){
res.append(sbs[i].toString());
}
return res.toString();
}
}