Clean python iterative solution with stack


  • 0
    class Solution(object):
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            
            if '[' not in s:
                return NestedInteger(int(s))
            
            stringList = s.replace(',', ' ').replace('[', ' [ ').replace(']', ' ] ').split()
            parseStack = []
            
            for char in stringList:
                if char == '[':
                    parseStack.append(char)
                elif char == ']':
                    # pop a lis and NestedInteger
                    tempLis = []
                    while parseStack and parseStack[-1] != '[':
                        iVal = parseStack.pop()
                        tempLis.append(NestedInteger(iVal) if (type(iVal) is int) else iVal)
                            
                    # pop the '[' and create a new container
                    if parseStack: parseStack.pop()
                    newNestedInt = NestedInteger()
                    
                    # add NI to container and push into stack
                    while tempLis:
                        newNestedInt.add(tempLis.pop())
                    parseStack.append(newNestedInt)
                elif char:  # number
                    parseStack.append(int(char))
            return parseStack[0]
            
    

Log in to reply
 

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