Skip to content

Commit

Permalink
re-solve "6. Zigzag Conversion"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Sep 13, 2024
1 parent 09c6d43 commit 0b03a53
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 22 deletions.
4 changes: 4 additions & 0 deletions .plan
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Sep 13, 2024

* re-solve "6. Zigzag Conversion"

Sep 12, 2024

* re-solve "14. Longest Common Prefix"
Expand Down
38 changes: 16 additions & 22 deletions src/zigzag_conversion.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,28 @@
class Solution:
def convert(self, s: str, num_rows: int) -> str:
if num_rows <= 1:
if num_rows == 1:
return s

result = []
n = len(s)
result: list[str] = []

first, second = num_rows * 2 - 2, 0

start = 0
while start < num_rows and start < len(s):
i = start
step = (num_rows - 1) * 2

# first row
for i in range(0, n, step):
result.append(s[i])

while True:
i += first

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

i += second
# middle rows
for r in range(1, num_rows - 1):
for i in range(r, n, step):
result.append(s[i])

if second and i < len(s):
result.append(s[i])
j = i + (step - r * 2)
if j < n:
result.append(s[j])

if i >= len(s):
break

start += 1
first -= 2
second += 2
# last row
for i in range(num_rows - 1, n, step):
result.append(s[i])

return "".join(result)

0 comments on commit 0b03a53

Please sign in to comment.