ZigZag
6. ZigZag Conversion
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".
class Solution {
public:
string convert(string s, int numRows) {
size_t len = s.size();
if (len <= 1 || numRows <= 1) return s;
vector<string> row(numRows);
int i = 0;
int j = len;
while (i < j) {
for (int k = 0; k < numRows && i < j; ++k) {
row[k] += s[i++];
}
for (int k = numRows - 2; k > 0 && i < j; --k) {
row[k] += s[i++];
}
}
string res;
for (auto str : row) res += str;
return res;
}
};