[
string
stack
parser
]
Leetcode 0385 Mini Parser
Problem statement
https://leetcode.com/problems/mini-parser/
Solution
Another parser problem, quite painful, because a lot of API are given (see leetcode), but we need to use only two of them add(self, elem)
and NestedInteger(num)
. We need to read element by element, create NestedInteger
and run recursively helper function. Similar to Basic Calculator I, II, III problems (which are also parsers).
Complexity
Time and space complexity is O(n)
, where n
is length of string.
Code
class Solution:
def deserialize(self, s):
def parse(num = ""):
while self.iter < len(s) and s[self.iter] in "-1234567890":
num += s[self.iter]
self.iter += 1
if num: return NestedInteger(int(num))
if s[self.iter] == '[':
self.iter += 1
lst = NestedInteger()
while s[self.iter] != ']':
lst.add(parse())
if s[self.iter] == ',':
self.iter += 1
self.iter += 1
return lst
self.iter = 0
return parse()