mini parser using implicit system stack - Python


  • 0
    S
    class Solution(object):
        def recurse(self, s):
            nstin = NestedInteger()
            num = ''
            i = 0
            while i < len(s):
                c = s[i]
                if c.isdigit() or c == '-':
                    num += c
                elif c == ',' or c == ']':
                    if num:
                        nstin.add(NestedInteger(eval(num)))
                        num = ''
                    if c == ']':
                        return (nstin,i+1)
                elif c == '[':
                    obj, j = self.recurse(s[i+1::])
                    nstin.add(obj)
                    i += j
                i += 1
                    
                    
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
    
            nstin = NestedInteger()
            if s[0] == '[':
                nstin,_ = self.recurse(s[1::])
            else:
                nstin.setInteger(eval(s))
                
            return nstin
    

Log in to reply
 

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