-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathZigZagConversion.java
More file actions
100 lines (86 loc) · 2.89 KB
/
Copy pathZigZagConversion.java
File metadata and controls
100 lines (86 loc) · 2.89 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
// (you may want to display this pattern in a fixed font for better legibility)
// P A H N
// A P L S I I G
// Y I R
// See: https://leetcode.com/problems/zigzag-conversion/
package leetcode.string;
public class ZigZagConversion {
/**
* Relatively fast solution.
* O(n) time
* O(n) space
*/
public String convert(String s, int numRows) {
if (numRows == 1)
return s;
StringBuilder[] rows = new StringBuilder[numRows];
for (int i = 0; i < rows.length; i++)
rows[i] = new StringBuilder();
int i = 0;
int row = 0;
while (i < s.length()) {
while (i < s.length() && row < numRows)
rows[row++].append(s.charAt(i++));
row -= 2;
while (i < s.length() && row >= 0)
rows[row--].append(s.charAt(i++));
row+=2;
}
StringBuilder res = new StringBuilder();
for (StringBuilder currRow : rows)
res.append(currRow);
return res.toString();
}
/**
* Initial Solution (stupid bruteforce).
*/
public String convert_var1(String s, int numRows) {
if (numRows == 1)
return s;
char[] str = s.toCharArray();
char[][] arr = new char[numRows][s.length()];
int i = 0;
int row = 0;
int col = 0;
while (i < s.length()) {
// print vertical
while (i < s.length() && row < numRows)
arr[row++][col] = str[i++];
row -= 2;
col++;
// print diagonal
while (i < s.length() && row >= 0)
arr[row--][col++] = str[i++];
col--;
row += 2;
}
// Using the StringBuilder here doesn't gain a significant performance.
// The solution is still slow.
StringBuilder sb = new StringBuilder();
for (i = 0; i < numRows; i++)
for (int j = 0; j < col + 1; j++)
if (arr[i][j] != 0)
sb.append(arr[i][j]);
return sb.toString();
}
public static void main(String[] args) {
ZigZagConversion sln = new ZigZagConversion();
System.out.println(sln.convert("PAYPALISHIRING", 3).equals("PAHNAPLSIIGYIR"));
System.out.println(sln.convert("PAYPALISHIRING", 4).equals("PINALSIGYAHRPI"));
}
@SuppressWarnings("unused")
private static void printRes(char[][] res) {
for (int i = 0; i < res.length; i++) {
String row = "";
for (int j = 0; j < res[0].length; j++) {
if (res[i][j] != 0) {
row += res[i][j];
} else {
row += " ";
}
}
System.out.println(row);
}
}
}