Solution in Python


  • 0
    M
    class Solution:
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            #Inner_list and outer_list to make a 2D array.
            inner_list = []
            outer_list = []
            for i in range(numRows):
                outer_list.append([])
            """Here the corner cases will be when either length of input(s) will be zero or the numRows is 1 in which cases we can simply return the string(s) back as answer."""
            if len(s)==0 or numRows == 1:
                return s
    """Here I am appending the first char in s to [0,0] because in my main logic I won't be starting with [0,0] instead I will start with [0,1]"""
            outer_list[0].append(s[0])
            s=s[1:]
    """The loop will continue untill length of s goes to zero."""
            while len(s)!=0:
    """Here I am filling up the matrix top to bottom. And this loop will break if length of s becomes zero in between"""
                for i in range(1,numRows):
                    if len(s) == 0:
                        break
                    outer_list[i].append(s[0])
                    s=s[1:]
    """Here I am filling up the matrix bottom to top. And this loop will break if length of s becomes zero in between"""
                for i in range(len(outer_list)-2,-1,-1):
                    if len(s) == 0:
                        break
                    outer_list[i].append(s[0])
                    s=s[1:]
            final_ans = ""
    """Here I am iterating over the 2D mattrix(outer_list) to get the final string which I will return as an answer."""
            for i in range(len(outer_list)):
                for j in range(len(outer_list[i])):
                    final_ans+=outer_list[i][j]
            return final_ans
                    
                    
    

Log in to reply
 

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