Python, straight and simple, but slow with some comments


  • 0
    P
    class Solution(object):
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            #index = [1,2,3,4,5] for example numRow = 5
            index = [ i for i in range(1, numRows+1)] 
            # now index = [1,2,3,4,5,4,3,2] which is a fixed pattern for index when numRow = 5
            index += index[1:-1][::-1]
    
            # find out how many times this pattern will be needed
            index = index * (len(s)//len(index)+1)
           
            #assign index to every character
            zigzag = []
            for i,j in zip(index, s):
                zigzag.append((i,j))
            
            # sort based on the index
            zigzag.sort(key=lambda x:x[0])
            return "".join(list( map(lambda x:x[1], zigzag) ))
    

Log in to reply
 

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