题目:
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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
链接:ZigZag Conversion
解法:遍历重排,时间O(n)
class Solution {
public:
string convert(string s, int numRows) {
string ans;
vector<string> vs;
for (int i = 0; i < numRows; i++) {
string sub;
vs.push_back(sub);
}
int len = s.length(), cnt = 0;
bool up = false;
for (int i = 0; i < len; i++) {
vs[cnt] += s[i];
if (cnt == 0) up = false;
else if (cnt == numRows - 1) up = true;
if (numRows == 1) ;
else if (up) cnt--;
else cnt++;
}
for (int i = 0; i < numRows; i++) {
ans += vs[i];
}
return ans;
}
};
Runtime: 25 ms