My python solution

  • 1

    quite simple, if it's row 0/n-1, add step D each time. otherwise, add step MD and then D. in both case, repeat until it goes beyond the end of string. D = 2n-2. MD = 2n-2-2i (i being ith row).

    class Solution:
        # @return a string
        def convert(self, s, nRows):
            if nRows == 1:
                return s
            D = 2*nRows -2
            L = len(s)
            R = ''
            for i in range(0, nRows):
                MD = 2*nRows - 2 - 2*i
                t = i
                while t < L:
                    R += s[t]
                    if i != 0 and i!= nRows-1 and t+MD < L:
                        R += s[t+MD]
                    t += D
            return R

Log in to reply

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