-
Notifications
You must be signed in to change notification settings - Fork 0
/
6) Zigzag Conversion.py
37 lines (29 loc) · 1.23 KB
/
6) Zigzag Conversion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def convert(self, s: str, num_rows: int) -> str:
if num_rows == 1:
return s
n = len(s)
sections = ceil(n / (2 * num_rows - 2.0))
num_cols = sections * (num_rows - 1)
matrix = [[' '] * num_cols for _ in range(num_rows)]
curr_row, curr_col = 0, 0
curr_string_index = 0
# Iterate in zig-zag pattern on matrix and fill it with string characters.
while curr_string_index < n:
# Move down.
while curr_row < num_rows and curr_string_index < n:
matrix[curr_row][curr_col] = s[curr_string_index]
curr_row += 1
curr_string_index += 1
curr_row -= 2
curr_col += 1
# Move up (with moving right also).
while curr_row > 0 and curr_col < num_cols and curr_string_index < n:
matrix[curr_row][curr_col] = s[curr_string_index]
curr_row -= 1
curr_col += 1
curr_string_index += 1
answer = ""
for row in matrix:
answer += "".join(row)
return answer.replace(" ", "")