模拟题,根据z字型,将给定字符串先竖填充,再横读,画出row=4,5 的图之后,总结每行相邻元素对应给定字符串之间的位置关系,即可直接生成返回字符串,不需要存二维数组。
class Solution {
public:
string convert(string s, int numRows) {
string ans;
int t=(numRows-1)*2;
int n=s.length();
if(numRows>=n||numRows==1)return s;
for(int i=0;i<numRows;++i){
int temp=t-i*2;
if(temp==t||temp==0){
int j=0;
while(i+j<n){ans.push_back(s[i+j]);j+=t;}
}else{
int j=0;
while(i+j<n){
ans.push_back(s[i+j]);
j+=temp;
temp=t-temp;
}
}
}
return ans;
}
};