Python Solution Using Stack


  • 0
    A
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            nestedIntegerStack = []
            startOfInt = 0
            resultNestedInteger = NestedInteger()
        
            for i in range(0, len(s)):
                if s[i].isdigit() or s[i] == '-':
                    continue
                
                if i > startOfInt:
                    currentInt = int(s[startOfInt:i])
                else:
                    currentInt = None
                    
                startOfInt = i+1
                
                if len(nestedIntegerStack) > 0 and currentInt != None:
                    currentNestedInteger = nestedIntegerStack[-1]
                    currentNestedInteger.add(NestedInteger(currentInt))
    
                if s[i] == '[':
                    if len(nestedIntegerStack) > 0:
                        newNestedInteger = NestedInteger()
                    else:
                        newNestedInteger = resultNestedInteger
                    nestedIntegerStack.append(newNestedInteger)
    
                if s[i] == ']':
                    nestedInteger = nestedIntegerStack.pop()
                    if len(nestedIntegerStack) > 0:
                        currentNestedInteger = nestedIntegerStack[-1]
                        currentNestedInteger.add(nestedInteger)
            
            if startOfInt == 0:
                resultNestedInteger.setInteger(int(s))
            
            return resultNestedInteger
    

    The idea is that when encounter a '[', create a nestedInteger object and push to stack, when encounter a ']', pop an element out from the stack and add it to the top of the stack.


Log in to reply
 

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