Commented solution, Python


  • 0
    P

    '''
    def decodeString(self, s):

        # find the first "]"
        right = s.find("]") # index of right limit initialization
        left = 0 # index of left limit initialization
        
        # while there is a "]" to be found: (if there is no "]" to be found it means that 
        #we are done iterating and the method 'find' will return -1)
        while right != -1:
            # index of left limit is found ('rfind' is a method that finds the first 
            # ocurrence of its argument from right to left)
            left = s[:right].rfind("[")
            
            # the sequence of chars inside '[ ]' is found
            seq = s[left+1:right]
            
            # this inner while loop gets the 'number' of repetitions (it is a string)
            i = 1
            rep_num = ""
            # while the selected char is a digit
            while s[left-i].isdigit():
                # save the digit in rep_num
                rep_num = s[left-i] + rep_num
                # check the previous char
                i += 1
            
            # update new value of s removing the 'number' of repetitions and '[' (s[:left-i+1])
            # and ']' (s[right+1:])
            s = s[:left-i+1]+int(rep_num)*seq+s[right+1:]
            
            #update the right index value and repeat
            right = s.find("]")
        return s
    

    '''


Log in to reply
 

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