Recusive Python Solution


  • 1
    H
    class Solution(object):
        def decodeString(self, s):
            """
            :type s: str
            :rtype: str
            """
            res = ""
            start_index = 0
            num_end_index = 0
            is_parsing = False
            depth = 0
            for i in range(len(s)):
                if ord(s[i]) - ord('0') >= 0 and ord(s[i]) - ord('0') <=9: # we have a number here
                    if not is_parsing:
                        start_index = i
                        is_parsing = True
                elif s[i] == "[":
                    depth += 1
                    if depth == 1:
                        num_end_index = i
                elif s[i] == "]":
                    depth -= 1
                    if depth == 0:
                        is_parsing = False
                        sub_s = s[num_end_index + 1:i]
                        parse_result = self.decodeString(sub_s)
                        times = int(s[start_index:num_end_index])
                        res += parse_result * times
                else:
                    if not is_parsing:
                        res += s[i]
            return res
                        
    

Log in to reply
 

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