My Python solution with one stack that beat 99% Python submissions


  • 0
    C
    class Solution(object):
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            stack = []
            curlist = []
            num = None
            negtive = 1
            
            for c in s:
                if c.isdigit():
                    if num is None:
                        num = 0
                    num = num * 10 + int(c)
                elif c == '-':
                    negtive = -1
                elif c == ',': 
                    if num is not None:
                        curlist.append(num*negtive)
                    num = None
                    negtive = 1
                elif c == '[':
                    stack.append(curlist)
                    curlist = []
                    num = None
                elif c == ']':
                    prevlist = stack.pop()
                    if num is not None:
                        curlist.append(num*negtive)
                    prevlist.append(curlist)
                    curlist = prevlist
                    num = None
                    negtive = 1
            if not '[' in s:
                return num * negtive
            else:
                return prevlist[0]
    

  • 0

    I must point out thar your return type is not NestedInteger. If ignore it, the fastest way is json.loads which only costs 75ms and beats 100% submissions.

    class Solution(object):
        def deserialize(self, s):
            """
            :type s: str
            :rtype: NestedInteger
            """
            import json
            return json.loads(s)
    

Log in to reply
 

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