-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode6.java
30 lines (30 loc) · 1.08 KB
/
LeetCode6.java
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
public class LeetCode6 {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
StringBuilder result = new StringBuilder();
int count = 0;
int rep = (numRows + numRows - 2);
int rest = (s.length() % rep) > numRows ? 1 + (s.length() % rep) % numRows : 1;
int n = s.length() / rep * (numRows - 1) + rest;
Character[][] arr = new Character[numRows][n];
for (int y = 0; y < n; y++) {
for (int x = 0; x < numRows; x++) {
if (count < s.length()) {
if (y % (numRows - 1) == 0) {
arr[x][y] = s.charAt(count++);
} else if ((x + y) % (numRows - 1) == 0) {
arr[x][y] = s.charAt(count++);
}
}
}
}
for (int x = 0; x < numRows; x++) {
for (int y = 0; y < n; y++) {
if (arr[x][y] != null) {
result.append(arr[x][y]);
}
}
}
return result.toString();
}
}