-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution6.java
45 lines (39 loc) · 1.15 KB
/
Solution6.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
package leetcode.str;
public class Solution6 {
public static void main(String[] args) {
System.out.println(new Solution6().convert("PAYPALISHIRING", 3));
}
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
StringBuilder[] builders = new StringBuilder[numRows];
for (int i = 0; i < builders.length; i++) {
builders[i] = new StringBuilder();
}
boolean down = true;
int index = 0;
char[] charArray = s.toCharArray();
for (char c : charArray) {
builders[index].append(c);
if (down) {
index++;
if (index == builders.length) {
down = !down;
index -= 2;
}
} else {
index--;
if (index == -1) {
down = !down;
index += 2;
}
}
}
StringBuilder res = new StringBuilder();
for (StringBuilder builder : builders) {
res.append(builder);
}
return res.toString();
}
}