Skip to content

Commit 3e693f3

Browse files
authored
Update ZigZag Conversion.java
1 parent 5038df5 commit 3e693f3

File tree

1 file changed

+22
-23
lines changed

1 file changed

+22
-23
lines changed

Medium/ZigZag Conversion.java

Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
11
class Solution {
2-
public String convert(String s, int numRows) {
3-
List<StringBuilder> list = new ArrayList<>();
4-
for (int i = 0; i < numRows; i++) {
5-
list.add(new StringBuilder());
6-
}
7-
8-
int idx = 0;
9-
while (idx < s.length()) {
10-
for (int i = 0; i < numRows && idx < s.length(); i++) {
11-
list.get(i).append(s.charAt(idx++));
12-
}
13-
14-
for (int i = numRows - 2; i > 0 && idx < s.length(); i--) {
15-
list.get(i).append(s.charAt(idx++));
16-
}
17-
}
18-
19-
StringBuilder ans = new StringBuilder();
20-
for (StringBuilder sb : list) {
21-
ans.append(sb.toString());
22-
}
23-
24-
return ans.toString();
2+
public String convert(String s, int numRows) {
3+
if (numRows == 1) {
4+
return s;
255
}
6+
List<StringBuilder> list = new ArrayList<>();
7+
for (int i = 0; i < numRows; i++) {
8+
list.add(new StringBuilder());
9+
}
10+
int idx = 0;
11+
boolean downDirection = false;
12+
for (char c : s.toCharArray()) {
13+
list.get(idx).append(c);
14+
if (idx == 0 || idx == numRows - 1) {
15+
downDirection = !downDirection;
16+
}
17+
idx += downDirection ? 1 : -1;
18+
}
19+
StringBuilder result = new StringBuilder();
20+
for (StringBuilder sb : list) {
21+
result.append(sb.toString());
22+
}
23+
return result.toString();
24+
}
2625
}

0 commit comments

Comments
 (0)