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" |
大意
以齿轮性输出字符串。
例如:
答案
1 | class Solution { |
思路
首先要求z子型输出,其实可以把拐弯的地放都看成直的。
1 | A B Y A A A |
一行一行的输出,首先根据行数可以计算出一个group的个数,比如上面的图中一个PAYP就是一个group,然后就是以一个group为一个循环。首先判断,字符串长度没有行数长时,就可以直接输出。
接着是for循环,分为三部分,第一行,最后一行,中间行,分别进行输出。
需要特别注意的是注释1的地方,注释1上面的for循环只确保了i<len,并没有确保i+row<len 所以加一个if判断,否则会输出乱码。
Author: corn1ng
Link: https://corn1ng.github.io/2017/12/08/算法/leetcode6/
License: 知识共享署名-非商业性使用 4.0 国际许可协议