-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigZagConversion.java
More file actions
39 lines (33 loc) · 1006 Bytes
/
ZigZagConversion.java
File metadata and controls
39 lines (33 loc) · 1006 Bytes
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
import java.util.Arrays;
public class ZigZagConversion {
public static void main(String[] args) {
String s = "PAYPALISHIRING";
int numRows = 4;
if(numRows == 1) return s;
StringBuilder[] a = new StringBuilder[numRows];
int current = 0;
int dir = 0;
String ret = "";
if(numRows == 1) {
System.out.println(s);
}
for(int i = 0; i < a.length; i++) {
a[i] = new StringBuilder();
}
for(int i = 0; i < s.length(); i++) {
a[current] = a[current].append(s.charAt(i));
current += dir;
if(current == 0 || current == numRows-1) {
dir = (dir == 0) ? 1 : -dir;
}
}
return convert(a);
}
private String convert(StringBuilder[] sbs) {
StringBuilder result = "";
for(StringBuilder sb : String ) {
result.append(sb.toString());
}
return result.toString();
}
}