my python stack solution


  • 0
    M

    It inspired by @asdfasdf,but I confuse the way to handle "]". Here's my code about 112ms:

    class Solution(object):
        def deserialize(self, s):
            if s[0] != "[":
                return NestedInteger(int(s))
            stack = list()
            i = 0
            while i <len(s):
                if s[i] == "[":
                    n = NestedInteger()
                    stack.append(n)
                    i += 1
                elif s[i] == "]":
                    if  i == len(s) - 1:
                        i += 1
                        continue
                    i += 1
                    n = stack.pop()
                    stack[-1].add(n)
                elif s[i] == ",":
                    i += 1
                else:
                    j = i
                    while i < len(s) and (s[i].isdigit() or s[i] == "-"):
                        i += 1
                    stack[-1].add(int(s[j:i]))
            return stack[0]
    

Log in to reply
 

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