Skip to content

Commit

Permalink
Index based "Zigzag Conversion" solution
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Mar 23, 2024
1 parent 3b318d6 commit c98d91e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
37 changes: 28 additions & 9 deletions src/zigzag_conversion.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,34 @@
class Solution:
def convert(self, s: str, num_rows: int) -> str:
data: list[list[str]] = [[] for _ in range(num_rows)]
if num_rows <= 1:
return s

i = 0
shift = +1
result = []

for x in s:
data[i].append(x)
i = (i + shift) % num_rows
first, second = num_rows * 2 - 2, 0

if i == 0 or i == num_rows - 1:
shift *= -1
start = 0
while start < num_rows and start < len(s):
i = start

return "".join("".join(x) for x in data)
result.append(s[i])

while True:
i += first

if first and i < len(s):
result.append(s[i])

i += second

if second and i < len(s):
result.append(s[i])

if i >= len(s):
break

start += 1
first -= 2
second += 2

return "".join(result)
1 change: 1 addition & 0 deletions tests/test_zigzag_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
("PAYPALISHIRING", 3, "PAHNAPLSIIGYIR"),
("PAYPALISHIRING", 4, "PINALSIGYAHRPI"),
("A", 1, "A"),
("A", 2, "A"),
("AB", 1, "AB"),
),
)
Expand Down

0 comments on commit c98d91e

Please sign in to comment.