-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigzagConversion.java
More file actions
40 lines (37 loc) · 1.18 KB
/
ZigzagConversion.java
File metadata and controls
40 lines (37 loc) · 1.18 KB
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
import java.util.Arrays;
import java.util.Objects;
/*
* https://leetcode.com/problems/zigzag-conversion/
*/
public class ZigzagConversion {
public String convert(String s, int numRows) {
if (s == null || s.isEmpty() || numRows == 1) {
return s;
}
StringBuilder[] stringBuilders = new StringBuilder[numRows];
int j = 0;
boolean addition = true;
for (int i = 0 ; i < s.length() ; i++) {
char c = s.charAt(i);
if (stringBuilders[j] == null) {
stringBuilders[j] = new StringBuilder();
}
stringBuilders[j].append(c);
if (addition) {
j++;
if (j == numRows - 1) {
addition = false;
}
} else {
j--;
if (j == 0) {
addition = true;
}
}
}
return new String(Arrays.stream(stringBuilders).filter(Objects::nonNull).reduce(StringBuilder::append).get());
}
public static void main(String[] args) {
System.out.println(new ZigzagConversion().convert("AB", 1)); // PAHNAPLSIIGYIR
}
}