-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q6_ZigZagConversion.java
64 lines (51 loc) · 1.47 KB
/
Q6_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
54
55
56
57
58
59
60
61
62
63
64
package com.gyanblog.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* 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
And then read line by line: "PAHNAPLSIIGYIR"
*
* For explanation: https://www.gyanblog.com/gyan/coding-interview/leetcode-zigzag-pattern/
*/
public class Q6_ZigZagConversion {
private String str;
public Q6_ZigZagConversion(String str) {
this.str = str;
}
public String conversion(int numRows) {
int l = this.str.length();
List<StringBuffer> zigzag = new ArrayList<StringBuffer>();
for (int i=0; i<numRows; i++) {
zigzag.add(new StringBuffer());
}
boolean comingFromTop = true;
int zig = 0;
for (int i=0; i<l; i++) {
zigzag.get(zig).append(this.str.charAt(i));
if (zig == numRows-1) {
comingFromTop = false;
}
else if (zig == 0) {
comingFromTop = true;
}
zig = comingFromTop ? zig + 1 : zig - 1;
zig = zig % numRows;
}
StringBuffer sb = new StringBuffer();
for (int i=0; i<numRows; i++) {
sb.append(zigzag.get(i));
}
return sb.toString();
}
public static void main(String[] args) {
String str = "PAYPALISHIRING";
Q6_ZigZagConversion q = new Q6_ZigZagConversion(str);
System.out.println(q.conversion(3));
System.out.println("~~~~~~~~~~~~~~~~~");
System.out.println(q.conversion(4));
}
}