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
Example 3:
Input: s = "A", numRows = 1 Output: "A"
Constraints:
1 <= s.length <= 1000sconsists of English letters (lower-case and upper-case),','and'.'.1 <= numRows <= 1000
Approach 01: Simulate Zigzag Row by Row
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1 || numRows >= s.length()) return s;
vector rows(numRows);
int currRow = 0;
bool goingDown = false;
for (char c : s) {
rows[currRow] += c;
if (currRow == 0 || currRow == numRows - 1) goingDown = !goingDown;
currRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) ret += row;
return ret;
}
};
Time Complexity:
- O(n): We iterate through the string of length
nonce.
Space Complexity:
- O(n): We store the characters in
numRowsstrings, which in total store allncharacters.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
rows = [''] * numRows
currRow = 0
goingDown = False
for c in s:
rows[currRow] += c
if currRow == 0 or currRow == numRows - 1:
goingDown = not goingDown
currRow += 1 if goingDown else -1
return ''.join(rows)
Time Complexity:
- O(n): We iterate through the string once.
Space Complexity:
- O(n): We store the characters in a list of strings.
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
List rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++)
rows.add(new StringBuilder());
int currRow = 0;
boolean goingDown = false;
for (char c : s.toCharArray()) {
rows.get(currRow).append(c);
if (currRow == 0 || currRow == numRows - 1) goingDown = !goingDown;
currRow += goingDown ? 1 : -1;
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows) ret.append(row);
return ret.toString();
}
}
Time Complexity:
- O(n): We iterate through the string once.
Space Complexity:
- O(n): We store the characters in
StringBuilderobjects.