
题目
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)
1 |
P A H N |
And then read line by line: PAHNAPLSIIGYIR
Write the code that will take a string and make this conversion given a number of rows:
1 |
string convert(string text, int nRows); |
convert("PAYPALISHIRING", 3) should return PAHNAPLSIIGYIR.
解题思路
0123456789 nRows = 2
1 |
0 2 4 6 8 |
Output:0 2 4 6 8 1 3 5 7 9
0123456789 nRows = 3
1 |
0 4 8 |
Output:0 4 8 1 3 5 7 9 2 6
0123456789 nRows = 4
1 |
0 6 |
Output:0 6 1 5 7 2 4 8 3 9
每个Zigzag包含的字符为 size = nRows + nRows - 2
每次跨度一个之,第一行和最后一行只需要添加一个字符,中间每一行需要添加两个字符
第二个字符和前面添加这个字符在s的index相差size - 2 * index
代码
1 |
public String convert(String s, int numRows) { |




近期评论