Python Stack Solution


  • 0
    class Solution(object):
        def deserialize(self, s):
            i = 0
            stack = []
            op = 1
            while i < len(s):
                if s[i] == '-':
                    op = -1
                elif s[i].isdigit():
                    num = int(s[i])
                    while i+1 < len(s) and s[i+1].isdigit():
                        num = num*10 + int(s[i+1])
                        i += 1
                    stack.append(num*op)
                    op = 1
                elif s[i] == '[':
                    stack.append(s[i])
                elif s[i] == ']':
                    a = []
                    while stack:
                        x = stack.pop()
                        if x == '[':
                            break
                        a = [x] + a
                    stack.append(a)
                i += 1
            return stack.pop()

Log in to reply
 

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