leetcode|【Leetcode】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)

PAHN A P L S I I G YIR

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".
题意:将一个字符串按给定行数蜿蜒排列,返回排列后按行输出的字符串。
我觉得这题的关键点在于弄清楚zigzag pattern的含义,下面我画图先解释一下:
(设输入字符串s="abcdefghijklmn……")
1、若nRows=1,则排列格式为abcdefghijklmn...;
2、若nRows=2,则排列格式为
leetcode|【Leetcode】ZigZag Conversion
文章图片

3、若nRows=3,则排列格式为
leetcode|【Leetcode】ZigZag Conversion
文章图片

4、若nRows=4,则排列格式为
leetcode|【Leetcode】ZigZag Conversion
文章图片

5、若nRows=5,6,7....同理
由上我们可以观察到,这个排列是是有规律可循的,当nRows=1,2时,字符串以原本的顺序排列和插空排列。
【leetcode|【Leetcode】ZigZag Conversion】nRows>2时,每个循环的元素个数为2(nRows-1)。因此,我们可以建立一个动态数组vector,里面包含nRows个
string类型的元素,然后对字符串s进行遍历,并将字符插入到对应的string中,最后将所有string相加,即可得到所要
的结果字符串。

class Solution { public: string convert(string s,int nRows) { if(s=="") return s; int len=s.size(); if(nRows==1) return s; else if(nRows==2) { string res=""; for(int i=0; i




    推荐阅读