Python solution with detailed explanation


  • 0
    G

    Solution

    ZigZag Conversion https://leetcode.com/problems/zigzag-conversion/

    • Simple solution - maintain two direction pointers.
    • Invariant - the row index is set before we encounter the next character
    • Special case for numRows = 1
    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            if numRows == 1:
                return s
            result = [[] for _ in range(numRows)]
            dir_down, curr_row = True, 0
            for x in s:
                result[curr_row].append(x)
                if dir_down:
                    curr_row += 1
                    if curr_row == numRows:
                        dir_down = False
                        curr_row = numRows-2
                else:
                    curr_row -= 1
                    if curr_row == -1:
                        dir_down = True
                        curr_row = 1
            return "".join(["".join(y) for y in result])
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.