Python solution using stack


  • 20
    class Solution(object):
        def decodeString(self, s):
            stack = []; curNum = 0; curString = ''
            for c in s:
                if c == '[':
                    stack.append(curString)
                    stack.append(curNum)
                    curString = ''
                    curNum = 0
                elif c == ']':
                    num = stack.pop()
                    prevString = stack.pop()
                    curString = prevString + num*curString
                elif c.isdigit():
                    curNum = curNum*10 + int(c)
                else:
                    curString += c
            return curString
    

  • 1
    A

    This is a great solution. Thanks!


  • 0

    @adarshmurthy You're welcome!


Log in to reply
 

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