Python Recursive Parsing (beats 90%)


  • 0
    U
    class Solution(object):
        def decodeString(self, s):
            """
            :type s: str
            :rtype: str
            """
            def decode(k):
                sub_output = repeat = ''
                while k < len(s):
                    c = s[k]
                    
                    if c.isdigit():
                        repeat += c
                        k += 1
                    
                    elif c == '[':
                        decoded_substring, k = decode(k+1)
                        sub_output += int(repeat) * decoded_substring
                        repeat = ''
                    
                    elif c == ']':
                        return sub_output, k+1
                    
                    else:
                        sub_output += c
                        k += 1
       
                return sub_output, k
            
            return decode(0)[0]
    

Log in to reply
 

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