-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZigzagConversion.java
53 lines (40 loc) · 1.25 KB
/
ZigzagConversion.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package leetcode;
import java.util.HashMap;
import java.util.Map;
public class ZigzagConversion {
public static String convert(String s, int numRows) {
if (s.length() < numRows) return s;
Map<Integer, String> map = new HashMap<>();
String resultStr = "";
int position = 0;
boolean isDirection = true;
for (int i = 0; i < s.length(); i++) {
map.put(position, map.getOrDefault(position, "") + s.charAt(i));
if (position+1 == numRows && position > 0) isDirection = false;
else if (position == 0 && !isDirection) isDirection = true;
if (isDirection) position++;
else position--;
}
position = 0;
for (int i = 0; i < map.size(); i++) {
resultStr += map.get(position);
position++;
}
return resultStr;
}
public static void main(String[] args) {
String[] sArr = {
"PAYPALISHIRING",
"PAYPALISHIRING",
"AB"
};
int[] nArr = {
3,
4,
1
};
for (int i = 0; i < sArr.length; i++) {
System.out.println(convert(sArr[i], nArr[i]));
}
}
}