LeetCode 6. ZigZag Conversion
Description
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"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return"PAHNAPLSIIGYIR"
.
输入之字字符串和之字的行数,要求按行输出字符串。
"A-Z"
5行的之字字符:
0 1 2 3 4 5 6 7 8 ...
0 A I Q Y
1 B H J P R X Z
2 C G K O S W
3 D F L N T V
4 E M U
可以看出:
- 第0、第4、第8、第12列每行都有字符,其他列只有一个字符
col % (5 - 1) == 0
- 其他列字符所在行:
row = (5 - 1) - (col % (5 - 1))
- 字符在输入字符串中的位置(
0
起)等于:index = col * 2 + row
Solution
|
|