Mini Parser LeetCode solution in Python

1
class Solution:
2
"""
3
we can approach this problem using stack
4
"""
5

6
def dfs(self, i, s):
7
res = NestedInteger()
8
while i < len(s):
9
if s[i] == "[":
10
y, i = self.dfs(i + 1, s)
11
res.add(y)
12
elif i < len(s) and s[i] == "]":
13
i += 1
14
return res, i
15
elif i < len(s) and s[i] == ",":
16
i += 1
17
else:
18
if i < len(s):
19
start = i
20
while s[i] != "," and s[i] != "]":
21
i += 1
22
res.add(NestedInteger(int(s[start:i])))
23
return res, i
24

25
def deserialize(self, s: str) -> NestedInteger:
26
if s[0] == "[":
27
res, i = self.dfs(1, s)
28
return res
29
else:
30
num = int(s)
31
res = NestedInteger()
32
res.setInteger(num)
33
return res

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0