-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzag_conversion_0006.py
More file actions
30 lines (30 loc) · 946 Bytes
/
zigzag_conversion_0006.py
File metadata and controls
30 lines (30 loc) · 946 Bytes
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
class Solution:
def convert(self, s: str, numRows: int) -> str:
"""
Reformat string s in zigzag pattern with numRows rows,
and then read it line by line.
Args:
s: Input string
numRows: Number of rows
Returns:
Reformatted string
Examples:
>>> sol = Solution()
>>> sol.convert("PAYPALISHIRING", 3)
'PAHNAPLSIIGYIR'
>>> sol.convert("PAYPALISHIRING", 4)
'PINALSIGYAHRPI'
>>> sol.convert("A", 1)
'A'
"""
if numRows == 1:
return s
rows = ['' for _ in range(numRows)]
current_row = 0
direction = 1
for i in range(len(s)):
rows[current_row] += s[i]
current_row += direction
if current_row == 0 or current_row == numRows - 1:
direction *= -1
return ''.join(rows)