Naive Python solution using stack. Not short but easy to understand


  • 0
    W

    Just use the three test cases given in the problem description and print the curw or stack you can easily understand the workflow.
    '''

    def decodeString(self, s):
    
        curw = ''
        curn = ''
        stack = []
    
        for i in xrange(len(s)):
            if '0' <= s[i] <= '9':
                curn += s[i]
                if i >= 1 and curw:
                    stack.append(curw)
                    curw = ''
            elif 'a' <= s[i] <= 'z':
                curw += s[i]
                #print curw
            elif s[i] == '[':
                if curn != '':
                    stack.append(int(curn))
                curn = ''
            elif s[i] == ']':
                while True:
                    if (not stack):
                        break
                    last = stack.pop()
                    if type(last) == int:
                        newstr = ''
                        for j in xrange(last):
                            newstr += curw
                        curw = newstr
                        #print curw
                        break
                    else:
                        curw = last + curw
                        #print curw
            #print stack
        
        while stack:
            curw = stack.pop() + curw
        return curw
    

    '''


Log in to reply
 

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