6. ZigZag Conversion
P A H N
A P L S I I G
Y I Rstring convert(string s, int numRows);Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P Istring convert(string s, int numRows) { // time: O(n); space: O(n)
if (s.empty()) return "";
int n = s.length(), i = 0;
vector<string> tmp(numRows, "");
while (i < n) {
// Vertical
for (int j = 0; j < numRows && i < n; ++j) {
tmp[j].push_back(s[i++]);
}
// Oblique
for (int j = numRows - 2; j >= 1 && i < n; --j) {
tmp[j].push_back(s[i++]);
}
}
string res;
for (const string& str : tmp) res += str;
return res;
}Last updated