6. ZigZag Conversion
1. Description
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).
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);
2. Example
Example 1
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Example 3
Input: s = “A”, numRows = 1
Output: “A”
3. Constraints
- 1 <= s.length <= 1000
- s consists of English letters (lower-case and upper-case), ‘,’ and ‘.’.
- 1 <= numRows <= 1000
4. Solutions
String
n = s.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public:
string convert(const string &s, int rows) {
const int n = s.size();
const int cycle = 2 * rows - 2;
if (rows == 1 || rows >= s.size()) {
return s;
}
string zigzag;
zigzag.reserve(n);
for (int row = 0; row < rows; ++row) {
for (int i = row; i < n; i += cycle) {
zigzag.push_back(s[i]);
int diagonal = i + cycle - 2 * row;
if (row != 0 && row != rows - 1 && diagonal < n) {
zigzag.push_back(s[diagonal]);
}
}
}
return zigzag;
}
};