Natural zigzag filling


  • 0
    I
    class Solution:
        def convert(self, s, numRows):
            """ The natural way to write the zigzag pattern is simply write the string up-down-up, up-down-up, ... 
            so we can use a structure such as an array of strings, a hash table of list of strings, a 2d array, etc. 
            In this case we use an array of strings and read each element of the string just once and fill the array. 
    
            Complexity O(n), Space O(n).
    
            :type s: str
            :type numRows: int
            :rtype: str
            """
            n   = len( s )     # number of elements
            a   = [ '' ] * n     # array with zigzag text
            i   = 0
            row = 0
    
            while i < n:
                # going down
                row = 0
                while i < n and row <numRows:
                    a[ row ] += s[i]
                    i   += 1
                    row += 1
    
                # going up
                row = numRows - 2
                while i < n and 0 < row:
                    a[ row ] += s[i]
                    i   += 1
                    row -= 1
    
            return ''.join( a )
    
    

Log in to reply
 

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