-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMini Parser.py
33 lines (31 loc) · 934 Bytes
/
Mini Parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
"""
we can approach this problem using stack
"""
def dfs(self, i, s):
res = NestedInteger()
while i < len(s):
if s[i] == '[':
y, i = self.dfs(i+1, s)
res.add(y)
elif i < len(s) and s[i] == ']':
i+=1
return res, i
elif i < len(s) and s[i] == ',':
i+=1
else:
if i < len(s):
start = i
while s[i] != ',' and s[i] != ']':
i+=1
res.add(NestedInteger(int(s[start:i])))
return res, i
def deserialize(self, s: str) -> NestedInteger:
if s[0] == '[':
res, i = self.dfs(1, s)
return res
else:
num = int(s)
res = NestedInteger()
res.setInteger(num)
return res