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
34
35
36
| # 一行解决 双百效率摘自评论区
def deserialize(s: str) -> NestedInteger:
return json.loads(s)
# 不想写了 取自题解
class Solution:
def deserialize(self, s: str) -> NestedInteger:
# 纯数字
if s[0] != '[':
return NestedInteger(int(s))
stack, curVal, sign = [], 0, False
for i, c in enumerate(s):
match c:
case '[':
# 递归嵌套
stack.append(NestedInteger())
case '-':
# 数字符号
sign = True
case ',':
# 只有上一个字符是数字才加入了新的数字,否则可能是 "],"
if s[i - 1].isdigit():
stack[-1].add(NestedInteger(-curVal if sign else curVal))
curVal, sign = 0, False
case ']':
# 只有上一个字符是数字才加入了新的数字,否则可能是 "[]"
if s[i - 1].isdigit():
stack[-1].add(NestedInteger(-curVal if sign else curVal))
# 弹出栈,并将当前的对象加入嵌套的列表中
if len(stack) > 1:
cur = stack.pop()
stack[-1].add(cur)
curVal, sign = 0, False
case _:
# 数字计算
curVal = curVal * 10 + int(c)
return stack.pop()
|