Skip to content

Commit f7d48aa

Browse files
author
deepshekhardas
committed
feat: add zigzag conversion algorithm
1 parent c0db072 commit f7d48aa

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

strings/zigzag_conversion.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from __future__ import annotations
2+
3+
4+
def zigzag_convert(s: str, num_rows: int) -> str:
5+
"""
6+
Convert a string to zigzag pattern and read it row by row.
7+
8+
The string is written in a zigzag pattern on num_rows rows:
9+
- Characters at index 0, num_rows, 2*num_rows, ... go to row 0
10+
- Characters at index 1, num_rows+1, 2*num_rows+1, ... go to row 1
11+
- And so on until row num_rows-1
12+
- Then the direction reverses (going up)
13+
14+
Args:
15+
s: The input string to convert
16+
num_rows: Number of rows in the zigzag pattern
17+
18+
Returns:
19+
The string read row by row from top to bottom
20+
21+
>>> zigzag_convert("PAYPALISHIRING", 3)
22+
'PAHNAPLSIIGYIR'
23+
>>> zigzag_convert("PAYPALISHIRING", 4)
24+
'PINALSIGYAHRPI'
25+
>>> zigzag_convert("A", 1)
26+
'A'
27+
>>> zigzag_convert("AB", 1)
28+
'BA'
29+
"""
30+
if num_rows == 1 or num_rows >= len(s):
31+
return s
32+
33+
rows: list[list[str]] = [[] for _ in range(num_rows)]
34+
current_row = 0
35+
going_down = False
36+
37+
for char in s:
38+
rows[current_row].append(char)
39+
if current_row == 0 or current_row == num_rows - 1:
40+
going_down = not going_down
41+
current_row += 1 if going_down else -1
42+
43+
return "".join("".join(row) for row in rows)
44+
45+
46+
if __name__ == "__main__":
47+
import doctest
48+
49+
doctest.testmod()

0 commit comments

Comments
 (0)