leetcode#6ZigZag Conversion
将字符串 “PAYPALISHIRING” 以Z字形排列成给定的行数:
P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:”PAHNAPLSIIGYIR”
实现一个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = “PAYPALISHIRING”, numRows = 3
输出: “PAHNAPLSIIGYIR”
示例 2:
输入: s = “PAYPALISHIRING”, numRows = 4
输出: “PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
class Solution { public: //直接准备numRows个桶,从上向下放元素,到底了再向上放,准备一个方向标识和一个当前桶标识j即可。我没看右没有简短的写法。这毕竟是体力题。。。 string convert(string s, int numRows) { if (numRows==1) return s; vector<string> vec(numRows); int direction=1;//1向下,-1向上 for(int i=0,j=0;i!=s.size();++i) { vec[j].push_back(s[i]); if(1==direction) { if(j==numRows-1) { direction=-1; j--; continue; } else j++; } if(-1==direction) { if(j==0) { direction=1; j++; } else j--; } } string result; for(auto iter=vec.begin();iter!=vec.end();++iter) result+=*iter; return result; } };