Python iterative solution with stack and dummy NestedInteger


  • 4
    A
    from collections import deque
    
    class Solution(object):
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            initial = NestedInteger()
            q = deque()
            q.append(initial)
            i = 0
    
            while(i < len(s)):
                if s[i] == '[':
                    n = NestedInteger()
                    q[-1].add(n)
                    q.append(n)
                    i += 1
                elif s[i] == ']':
                    q.pop()
                    i += 1
                elif s[i] == ',':
                    i += 1
                else:
                    j = i
                    while j < len(s) and ('0' <= s[j] <= '9' or s[j] == '-'):
                        j += 1
                    q[-1].add(int(s[i:j]))
                    i = j
    
            return q[0].getList()[0]

  • 1
    L

    Not sure why you need deque, could have just a list. You're using it like a stack not a queue.


Log in to reply
 

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