题目描述
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
思路
本题重点在于使用字符串vector来保存ZigZag之后的字符数组,并将二维转换等价为一维,因此只需要控制行的移动即可,此外,还需注意每次移动的方向,定义bool变量来控制。
程序代码
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1)
return s;
int len = s.length();
//使用vector存储二维数组,vector的构造函数是容量大小
vector<string> rows(min(len,numRows));
int currRow = 0;
bool goUp = false;
for(int i=0;i<len;i++){
rows[currRow] += s.at(i);
// printf("row:%d,char:%c\n",currRow,s.at(i) );
//判断当前位置是否向下还是向上
if(currRow == numRows - 1){
goUp = true;
}else if(currRow == 0){
goUp = false;
}
if(goUp){
currRow --;
}else{
currRow ++;
}
}
string result ;
for(int i=0;i<rows.size();i++){
result += rows[i];
}
return result;
}
};