Python traditional stack solution


  • 0
    class Solution(object):
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            stack = []
            i = 0
            while i < len(s):
                if s[i] == '[':
                    stack.append('[')
                    i += 1
                elif s[i].isdigit() or s[i] == '-':
                    begin = i
                    while i < len(s) and (s[i].isdigit() or s[i] == '-'):
                        i += 1
                    stack.append(int(s[begin: i]))
                elif s[i] == ']':
                    a = stack.pop()
                    ta = []
                    while a != '[':
                        ta.append(a)
                        a = stack.pop()
                    temp = NestedInteger()
                    while len(ta) != 0:
                        a = ta.pop()
                        temp.add(a)
                    if len(stack) == 0:
                        return temp
                    stack.append(temp)
                    i += 1
                elif s[i] == ',':
                    i += 1
            if len(stack) == 1:
                return NestedInteger(stack[0])

Log in to reply
 

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