The solution is just simulating zigzag traversal steps. Be careful that when numRows <= 1, the code should return the original string.
Time Complexity = O(len(s))
Space Complexity = O(len(s))
from operator import add
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows <= 1:
return s
memo = [""] * numRows
i = 0
row = 0
direction = 1
col = 0
while i < len(s):
memo[row] += s[i]
row = row + direction
if row == numRows:
row = numRows - 2
direction = - 1
if row < 0:
row = 1
direction = 1
i += 1
return reduce(add, memo)
No comments:
Post a Comment