Skip to content

Commit 2f3fac6

Browse files
committed
add solution of problem 6: zig zag conversion
1 parent 820b3bd commit 2f3fac6

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

ZigZagConversion6/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
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)
2+
```
3+
P A H N
4+
5+
A P L S I I G
6+
7+
Y I R
8+
```
9+
And then read line by line: `"PAHNAPLSIIGYIR"`
10+
Write the code that will take a string and make this conversion given a number of rows:
11+
12+
```
13+
string convert(string text, int nRows);
14+
```
15+
16+
`convert("PAYPALISHIRING", 3)` should return `"PAHNAPLSIIGYIR"`.

ZigZagConversion6/Solution.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
public class Solution {
2+
public String convert(String s, int numRows) {
3+
if (s == null || numRows == 1) {
4+
return s;
5+
}
6+
7+
StringBuilder sb = new StringBuilder();
8+
9+
10+
11+
for (int row = 0; row < numRows && row < s.length(); row++) {
12+
int index = row;
13+
int step1 = (numRows - 1 - row) * 2;
14+
int step2 = row * 2;
15+
sb.append(s.charAt(index));
16+
17+
while (index < s.length()) {
18+
if (step1 > 0) {
19+
index += step1;
20+
if (index < s.length())
21+
sb.append(s.charAt(index));
22+
}
23+
24+
if (step2 > 0) {
25+
index += step2;
26+
if (index < s.length())
27+
sb.append(s.charAt(index));
28+
}
29+
}
30+
}
31+
32+
return sb.toString();
33+
}
34+
}

0 commit comments

Comments
 (0)