Python solution with clear comments (no maths tricks)

  • 3
    class Solution(object):
        def convert(self, s, numRows):
            :type s: str
            :type numRows: int
            :rtype: str
            # initialize a matrix with numRows * empty strings
            matrix = [""]*numRows
            # default moving direction, down
            inc = 1
            # i is the index of row in the matrix
            i = 0
            for x in range(len(s)):
                # append char in s to corresponding row of matrix
                matrix[i] += s[x]
                # if out of boundary, change moving direction
                if i+inc >=numRows or i+inc < 0:
                    inc = -inc
                i += inc
            # append each strings in matrix to the result string     
            res = ""
            for ma in matrix:
                res += ma
            return res

Log in to reply

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