/*
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进行模拟操作
static int x = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(0);
return 0;
}();
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1){
return s;
}
vector<char> vec[numRows];
int i = 0;
bool flag = true;
for(int count = 0; count < s.size(); count++){
if(flag){
vec[i].push_back(s.at(count));
i++;
if(i == numRows){
i -= 2;
flag = false;
}
}else{
vec[i].push_back(s.at(count));
i--;
if(i == -1){
i += 2;
flag = true;
}
}
}
string str = "";
for(int j = 0; j < numRows; j++){
string temp(vec[j].begin(),vec[j].end());
str += temp;
}
return str;
}
};