zigzag-conversion
2019-07-24 本文已影响0人
DaiMorph
0 4 8
1 3 5 7 9
2 6 10
可以发现 当行数为3的时候 每4个数组成一个周期
行数为nRows的时候 周期t= 2*nRows-2
[0,nRows-1) 向下 [nRows,t) 向上
初始化一个 nRows 行的vector 依次将string中的每一个放入,在合并。
class Solution {
public:
string convert(string s, int nRows) {
if(nRows<=1)return s;
int t=2*nRows-2;
string res="";
vector<string>m(nRows,"");
for(int i=0;i<s.length();i++)
{
int a=i%t;
if(a<nRows)m[a]+=s[i];
else m[t-a]+=s[i];
}
for(int i=0;i<m.size();i++)res+=m[i];
return res;
}
};