LeetCode: 6. Zigzag Conversion
LeetCode: 6. Zigzag Conversion
Summary
Convert a string written in a zigzag pattern into the row-by-row reading order.
numRows controls the zigzag shape.
Approach
Find the correct row index for each character. Then build the final string from the per-row characters.
Function
Initialization:
current_row = 0zigzag_mode = 1(1means go down,-1means go up)row_patterns = [[] for _ in range(numRows)]
Main loop:
For each character ch in s:
- Add
chtorow_patterns[current_row]. - Move to the next row:
current_row += zigzag_mode. - Update direction when needed:
if
current_row == 0orcurrent_row == numRows - 1, thenzigzag_mode *= -1.
Convert row patterns to a string:
- Join each row.
- Join all rows together.
Complexity
Time Complexity: O(N). We traverse each character once, and joining rows is also O(N).
Space Complexity: O(N) for storing row patterns.