https://leetcode.com/problems/zigzag-conversion/
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 RAnd then read line by line:
"PAHNAPLSIIGYIR"
primitive idea: 模拟把这些character填进去一个char[] array里,最后逐行输出非空的character. (default value for char is '\u0000')
Space 其实有很多浪费,空字符
How to improve:
我们并不需要保存空字符,其实只要按照zigzag 的规律不断地把字符放进相应的行去 (就相当于把空字符压缩)
==> what is the DS => StringBuilder is enough (or k list)
/*n=numRows
Δ=2n-2 1 | 2n-1 | 4n-3
Δ=2n-4 2 2n-2 | 2n 4n-4 | 4n-2
Δ=2n-6 3 2n-3 | 2n+1 4n-5 | .
Δ= . . | . . | .
Δ= . n+2 | . 3n | .
Δ=2n-2(n-1)n-1 n+1 | 3n-3 3n-1 | 5n-5
Δ=2n-2 n | n-2 | 5n-4
I separate this pattern into smaller part as 1 to 2n - 2
filling the numbers in following steps:
- vertical down n - 1 times (1 .. n - 1)
- diagonal up n - 1 times (n .. 2n - 2)
- goto 1 again until reach to the end of string