Talentd
FleetCode

385. Mini Parser

Medium44.0% acceptance4 companies

Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger.

Each element is either an integer or a list whose elements may also be integers or other lists.

Example 1:

Input: s = "324"
Output: 324
Explanation: You should return a NestedInteger object which contains a single integer 324.

Example 2:

Input: s = "[123,[456,[789]]]"
Output: [123,[456,[789]]]
Explanation: Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
    i.  An integer containing value 456.
    ii. A nested list with one element:
         a. An integer containing value 789

Constraints:

  • 1 <= s.length <= 5 * 104
  • s consists of digits, square brackets "[]", negative sign '-', and commas ','.
  • s is the serialization of valid NestedInteger.
  • All the values in the input are in the range [-106, 106].

Asked at 4 companies

12:04
Still stuck?Read 4 approaches, or watch a walkthrough.
Open solution
Loading editor…
1# """
2# This is the interface that allows for creating nested lists.
3# You should not implement it, or speculate about its implementation
4# """
5#class NestedInteger:
6# def __init__(self, value=None):
7# """
8# If value is not specified, initializes an empty list.
9# Otherwise initializes a single integer equal to value.
10# """
11#
12# def isInteger(self):
13# """
14# @return True if this NestedInteger holds a single integer, rather than a nested list.
15# :rtype bool
16# """
17#
18# def add(self, elem):
19# """
20# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
21# :rtype void
22# """
23#
24# def setInteger(self, value):
25# """
26# Set this NestedInteger to hold a single integer equal to value.
27# :rtype void
28# """
29#
30# def getInteger(self):
31# """
32# @return the single integer that this NestedInteger holds, if it holds a single integer
33# Return None if this NestedInteger holds a nested list
34# :rtype int
35# """
36#
37# def getList(self):
38# """
39# @return the nested list that this NestedInteger holds, if it holds a nested list
40# Return None if this NestedInteger holds a single integer
41# :rtype List[NestedInteger]
42# """
43
44class Solution:
45 def deserialize(self, s: str) -> NestedInteger:
46
Starter codePython 3Spaces: 4
Examples
Input
"324"
Input
"[123,[456,[789]]]"
Your code is saved on this device.Solution