Python Recursive Solution

  • 0

    In my solution, a recursive call to the function occurs when a number is detected. The function processes every character in the string till the end of the line or until the closing bracket of the current substring is not found. Suggestions for improvement will be greatly appreciated.

    class Solution(object):
        def decodeString(self, s):
            :type s: str
            :rtype: str
            if s is None or len(s) == 0:
                return ''
            res, idx = self.decodeStringHelper(s, 0)
            return res
        def decodeStringHelper(self, s, idx):
            if idx == len(s):
                return ['', len(s)]
            res = ''
            i = idx
            while i < len(s) and s[i] != ']':
                if not s[i].isdigit():
                    res += s[i]
                    i += 1
                    multiplier = s[i]
                    i += 1
                    while s[i].isdigit():
                        multiplier += s[i]
                        i += 1
                    string, j = self.decodeStringHelper(s, i + 1)
                    res += string * int(multiplier)
                    i = j + 1
            return [res, i]

Log in to reply

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