python easy to understand - O(n) space-time


  • 0
    S
    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            l = len(s)
            r = numRows
            ans = []
            
            '''
            V   V   V 
            V ^ V ^ V ^
            V ^ V ^ V ^
            V ^ V ^ V ^
            V ^ V ^ V ^
            V   V   V
            
            A pair of columns comprising V and ^ constitutes a box of 2*(r-1) characters.
            '''
            if r == 1:
                return s
            else:
                box = l/(2*(r-1)) + (1 if (l%(2*(r-1))) else 0)
                col = box*2
                c_box = 2*(r-1)
                do_nothing = 0
                for R in range(r):
                    for C in range(col):
                        try:
                            if R == 0 or R == r-1:
                                do_nothing if C%2 else ans.append(s[R + c_box*C/2]) 
                            else:
                                ans.append(s[c_box*(C+1)/2-R]) if C%2 else ans.append(s[R + c_box*C/2])
                        except:
                            pass
            
            return ''.join(ans)
    

Log in to reply
 

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