字符串锯齿形转换

问题

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)

Example

1
2
3
4
5
6
7
input: "PAYPALISHIRING", 3
P A H N
A P L S I I G
Y I R
output: "PAHNAPLSIIGYIR"

1
2
3
4
5
6
7
8
9
input: "ABCDEFGHIJKL", 5
A I
B H J
C G K
D F L
E
output: "AIBHJCGKDFLE"

代码示例

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
package top.ygingko.leetcode;
import java.util.HashSet;
import java.util.Set;
public class ZigZagConversion {
public String convert(String s, int numRows) {
if (numRows <= 0) {
return null;
}
if (numRows == 1) {
return s;
}
int len = s.length();
char[] chs = s.toCharArray();
int index = 0;
char[] result = new char[len];
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < len; j += 2*(numRows-1)) {
int temp = j + i;
if (temp < len && !set.contains(temp)) {
result[index++] = chs[temp];
set.add(temp);
}
temp = j + 2*(numRows-1) - i;
if (temp < len && !set.contains(temp)) {
result[index++] = chs[temp];
set.add(temp);
}
}
}
return new String(result).trim();
}
public static void main(String[] args) {
ZigZagConversion conversion = new ZigZagConversion();
int num = 5;
String s = "PAYPALISHIRING";
s = "ABCDEFGHIJKL";
System.out.println(conversion.convert(s, num));
}
}