Skip to content

Commit 14f6ff5

Browse files
zigzag conversion
1 parent d34210c commit 14f6ff5

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

‎EASY/src/easy/ZigZagConversion.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package easy;
2+
3+
public class ZigZagConversion {
4+
5+
public String convert(String s, int numRows) {
6+
StringBuilder[] sb = new StringBuilder[numRows];
7+
char[] c= s.toCharArray();
8+
int len = s.length();
9+
for(int i = 0; i < numRows; i++){
10+
sb[i] = new StringBuilder();//this is an important step to initialize it
11+
}
12+
int i = 0;
13+
while(i < len){
14+
for(int index = 0; index < numRows && i < len; index++){
15+
sb[index].append(c[i++]);// vertically down
16+
}
17+
18+
for(int index = numRows - 2; index >= 1 && i < len; index--){/**Why it should start from numRows - 2? Think of the example when numRows = 3
19+
the starting point of obliquely going up is 1, which is numRows-2.*/
20+
sb[index].append(c[i++]);// obliquely up
21+
}
22+
}
23+
24+
for(i = 1; i < numRows; i++){
25+
sb[0].append(sb[i]);
26+
}
27+
return sb[0].toString();
28+
}
29+
30+
}

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
|9|[Palindrome Number](https://leetcode.com/problems/palindrome-number/)|[Solution](../../blob/master/EASY/src/easy/PalindromeNumber.java)| O(logn)/(n) | O(1) | Easy
7272
|8|[String to Integer (atoi)](https://leetcode.com/problems/string-to-integer-atoi/)|[Solution](../../blob/master/EASY/src/easy/StringToInteger.java)| O(n) | O(1) | Easy
7373
|7|[Reverse Integer](https://leetcode.com/problems/reverse-integer/)|[Solution](../../blob/master/EASY/src/easy/ReverseInteger.java) | O(1) | O(1) | Easy |
74+
|6|[ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/)|[Solution](../../blob/master/EASY/src/easy/ZigZagConversion.java) | O(n) | O(n) | Easy |
7475
|2|[Add Two Numbers](https://leetcode.com/problems/add-two-numbers/)|[Solution](../../blob/master/MEDIUM/src/medium/AddTwoNumbers.java) | O(n) | O(1) | Medium | LinkedList
7576
|1|[Two Sum](https://leetcode.com/problems/two-sum/)|[Solution](../../blob/master/EASY/src/easy/TwoSum.java)| O(n)/O(n^2)|O(1)/O(n) | Easy| HashMap
7677

0 commit comments

Comments
 (0)