-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0006-zigzag-conversion.java
52 lines (48 loc) · 1.7 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1)
return s;
StringBuilder res = new StringBuilder();
int increment = 2 * (numRows - 1);
for (int r = 0; r < numRows; r++) {
for (int i = r; i < s.length(); i += increment) {
res.append(s.charAt(i));
if (r > 0 && r < numRows - 1 && i + increment - 2 * r < s.length()) {
res.append(s.charAt(i + increment - 2 * r));
}
}
}
return res.toString();
}
}
--------------------------------------------------------------------------------------------------------------------------
//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();
}
}