一.解题思路
1.通过当前行的不断上下循环移动
2.将字符按序存放入vector中
3.最后再按行取出
二.代码及注释
class Solution { public: string convert(string s, int numRows) { //如果行数等于1或者行数和字符长度相等则直接返回s; if(numRows==1||s.size()<=numRows) return s; /* 1.用vector代替二维数组方便 2.定义长度为行数 */ vector<string> rows(numRows); //当前从第零行开始 int curRow = 0; //flag标志是向下还是向上进行->行移动 0为向下移动 1为向上移动 int flag = 0; //循环将每个字符放入vector中 字符是按序进行而行数是上下循环进行 for(int i=0;i<s.size();i++){ //存放字符 rows[curRow]+=s[i]; /* 1.当前行移动到最后一行时,改变flag从而开始向上移动 2.当前行移动到第一行时,改变flag从而开始向下移动 */ if(curRow==numRows-1){ flag = 1; }else if(curRow==0){ flag = 0; } //上下移动 if(flag==0){ curRow++; }else{ curRow--; } } //将字符按行取出 存放入t中 string t=""; for(string s:rows){ t+=s; } return t; } };