Mini Parser

Problem Id: 385 Difficulty: Medium


Intuition

Solution


class Solution:
    def deserialize(self, s: str) -> NestedInteger:
        if '[' not in s:
            return NestedInteger(int(s))
        elements = []
        l = 0
        tmp = ''
        for c in s:
            if c == '[' and l == 0:
                l += 1
            elif c == '[':
                l += 1
                tmp += c
            elif c == ']' and l == 1:
                l -= 1
                elements.append(tmp)
            elif c == ']':
                l -= 1
                tmp += c
            elif c == ',' and l == 1:
                elements.append(tmp)
                tmp = ''
            else:
                tmp += c
        elements = [elem for elem in elements if elem]
        # elements.append(tmp)
        ans = NestedInteger()
        for elem in elements:
            ans.add(self.deserialize(elem))
        return ans