1.题目
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
2.分析
可以发现这是一道比较简单的模拟题目,设立rol,col两个变量表示该填入第rol行第col列,且op作为字符串s遍历的指针,逐渐向右移动。可以发现当col%(numRows)==0时,直接从上到下填充,其他情况时需要对行列进行改变,即row–,col++
3.代码
class Solution {
public:
string convert(string s, int numRows) {
char ans[1010][1010];int op=0,row=0,col=0;string s_ans="";
if(numRows==1) return s;
for(int i=0;i<s.size();i++)
for(int j=0;j<numRows;j++)
ans[j][i]=' ';
while(op<s.size()){
if(col%(numRows-1)==0){
ans[row][col]=s[op];
if(row+1<numRows) row++;
else {row--;col++;}
}
else{
ans[row][col]=s[op];
row--;col++;
}
op++;
}
for(int i=0;i<numRows;i++)
for(int j=0;j<=col;j++)
if(ans[i][j]!=' ') s_ans=s_ans+ans[i][j];
return s_ans;
}
};