-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_06_ZigzagConversion.java
More file actions
57 lines (39 loc) · 1.42 KB
/
_06_ZigzagConversion.java
File metadata and controls
57 lines (39 loc) · 1.42 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class _06_ZigzagConversion {
static String convert(String str, int nunRows){
if (nunRows == 1 || nunRows >= str.length()) {
return str;
}
StringBuilder[] rows = new StringBuilder[nunRows];
for (int i = 0; i < nunRows; i++) {
rows[i] = new StringBuilder();
}
int currRow = 0;
boolean goingDown = false;
for (char c : str.toCharArray()) {
rows[currRow].append(c);
if (currRow == 0 || currRow == nunRows - 1) {
goingDown = !goingDown;
}
// Changing Row
currRow += goingDown ? 1 : -1;
}
// Join all rows
StringBuilder result = new StringBuilder();
for(StringBuilder row : rows){
result.append(row);
}
return result.toString();
}
public static void main(String[] args) {
String s1 = "PAYPALISHIRING";
int numRows1 = 3;
String result1 = convert(s1, numRows1);
System.out.println("Input: " + s1 + ", Rows = " + numRows1);
System.out.println("Output: " + result1);
String s2 = "PAYPALISHIRING";
int numRows2 = 4;
String result2 = convert(s2, numRows2);
System.out.println("Input: " + s2 + ", Rows = " + numRows2);
System.out.println("Output: " + result2);
}
}