6. 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)
1 | P A H N |
And then read line by line:
1 | "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); |
1 | convert("PAYPALISHIRING", 3) |
should return
1 | "PAHNAPLSIIGYIR" |
思路
就是把字符串原顺序012345……按下图所示排列:
比较直观的解法是,用一个字符串数组 string[rows] 来存储每一行,最后一拼接就是最终结果。
用一个flag表示正向还是反向,即上图中从第一行到最后一行还是最后一行到第一行。
solution
1 | class Solution { |
LeetCode代码和详细解题报告 Github地址:https://github.com/zhengjingwei/LeetCode