he string "PAYPALISHIRING"

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".

题目要求是Z字形输出,先竖排,到了nRows之后,之后的字符放在nRows-1行,单独成一列,依次递推,到底一行后,之后的元素放在前一个元素的下方,以此类推即可。

我们的思路就是使用Vector<string>,每一个string存储一行,(以上一个字符串为例,v[0]="PAHN",v[1]="APLSIIG",v[2]="YIR"),这样存储之后依次输出即可。辅助指针i从0开始递增,知道s.size().怎么往向量中添加是从代码中可以明显看出来。

class Solution {
public:
    string convert(string s, int nRows) {
      if(s == "" || nRows ==1)  //不用转换直接返回
        return s;
      std::vector<string> v(nRows);
      int n = s.size();
      int j = 0;
      for(int i = 0;i<n;)
      {
        while(i<n&&j<nRows)//垂直竖排的一列依次添加到向量中
        {
          v[j] = v[j]+s[i];
          j++;i++;
        }
        j = nRows-2;//从倒数第二行开始插入,因为最后一行已经添加过
        while(i<n&&j>0)//梯形的字符倒序添加到向量中
        {
          v[j] = v[j]+s[i];
          j--;i++;
        }
      }
      string str="";
      for(int k = 0;k<nRows;k++)//把向量中的添加到输出字符串中
        str = str+v[k];
      return str;
        
    }
};