Python iterative solution with stack


  • 0
    T
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            nums = set('1234567890-')
            stack = []
            i = 0
            while i < len(s):
                if s[i] == '[':
                    stack.append(s[i])
                elif s[i] in nums:
                    int_s = s[i]
                    while i < len(s) - 1 and s[i+1] in nums:
                        i += 1
                        int_s += s[i]
                    stack.append(int(int_s))
                elif s[i] == ']':
                    lst = []
                    while stack[-1] != '[':
                        lst.append(stack.pop())
                    stack.pop()
                    lst.reverse()
                    stack.append(lst)
                i += 1
            return stack[0]
    

Log in to reply
 

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