题目链接
题目大意
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
解题思路
思路一:看图找规律。
class Solution {
public:
string convert(string s, int numRows) {
string ans;
if(numRows==1) return s;
for(int i=0;i<numRows;i++){
int j=i;
bool flag=true;
if(i==0||i==numRows-1){
while(j<s.size()){
ans.push_back(s[j]);
j+=2*numRows-2;;
}
}
else{
while(j<s.size()){
ans.push_back(s[j]);
if(flag) j+=2*(numRows-i-1);
else j+=2*i;
flag=!flag;
}
}
}
return ans;
}
};
思路二:参考官方题解。设置一个字符串数组存储每行的子串。遍历 s 中的每一个字符,确定该字符属于哪一行,然后将该字符添加到对应行的子串后面。最后将该字符串数组合并为一个字符串即为答案。
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1) return s;
string rows[1000];
int row=0;
bool flag=true;
for(char c:s){
rows[row]+=c;
if(flag) row++;
else row--;
if(row==0||row==numRows-1) flag=!flag;
}
string ans;
for(int i=0;i<numRows;i++)
ans+=rows[i];
return ans;
}
};
解题感悟
1、注意 numRows==1 时的特殊情况。
2、通过设置标志变量进行不同操作。
3、word 画的图好丑,下次用 ppt 画。