Mini Parser Problem
Description
LeetCode Problem 385.
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 * 10^4
- 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 [-10^6, 10^6].
Solution
Approach: Stack of Open Lists
The input is either a single integer or a list. If it does not start with [, it is just a number: return NestedInteger(int(s)).
Otherwise, scan s from left to right and keep a stack of the lists that have been opened but not yet closed. The top of the stack is the innermost open list, the one that new elements belong to.
[: a new list starts. Push an emptyNestedInteger().- A digit or
-: a number starts. Read all of its characters (it can have several digits and a minus sign), and addNestedInteger(number)to the list on top of the stack. ]: the innermost list is complete. Pop it. If the stack is now empty, it was the outermost list, so return it. Otherwise add it to the new top, its parent.,: only separates elements; skip it.
For "[123,[456,[789]]]" the stack grows to three lists, [123, ...], [456, ...] and [789]. Each ] then folds the top list into the one below it.
Two details matter. Read the whole number, not one character at a time: "-12" is one element, not -, 1, 2. And add a finished list to its parent only when its ] is reached. That way the list is complete when it is added, which is safe even when add stores a copy.
Complexity: O(n) time and O(n) space, where n is the length of s: each character is read once, and the stack holds at most one list per open bracket. In C++, add takes a copy of the finished list, so deeply nested input also pays for copying each list once per level it is nested in.
class Solution:
def deserialize(self, s: str) -> NestedInteger:
if s[0] != "[":
return NestedInteger(int(s)) # the whole input is one integer
stack = [] # lists that are open, innermost last
i = 0
while i < len(s):
ch = s[i]
if ch == "[":
stack.append(NestedInteger())
i += 1
elif ch == "]":
finished = stack.pop()
if not stack:
return finished # the outermost list is closed
stack[-1].add(finished)
i += 1
elif ch == ",":
i += 1
else:
# A number, possibly negative: read all of its characters.
j = i
while j < len(s) and (s[j] == "-" or s[j].isdigit()):
j += 1
stack[-1].add(NestedInteger(int(s[i:j])))
i = j
return NestedInteger() # not reached for a valid input
Now write it from memory
Close the write-up and solve it yourself against the tests.