forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0006-zigzag-conversion.java
32 lines (30 loc) · 1.01 KB
/
0006-zigzag-conversion.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
//We check whether we are at the diagonal or not using a boolean and increment the pointer accordingly.
class Solution {
public String convert(String s, int row) {
if (row == 1) return s;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < row; i++) {
int j = i;
if (i == 0 || i == row - 1) {
while (j < s.length()) {
sb.append(s.charAt(j));
j += 2 * (row - 1);
}
} else {
boolean diagonal = false;
while (j < s.length()) {
if (!diagonal) {
sb.append(s.charAt(j));
j += 2 * (row - i - 1);
diagonal = true;
} else {
sb.append(s.charAt(j));
j += 2 * i;
diagonal = false;
}
}
}
}
return sb.toString();
}
}