1 class Solution: 2 def deserialize(self, s: str) -> NestedInteger: 3 4 if s[0] != '[': 5 return NestedInteger(int(s)) 6 7 stack = [] 8 # num为数字,sign为符号为,is_num为前一个是否为数字 9 num, sign, is_num = 0, 1, False 10 11 for c in s: 12 if c.isdigit(): 13 num = num * 10 + int(c) 14 is_num = True 15 elif c == '-': 16 sign = -1 17 elif c == '[': 18 stack.append(NestedInteger()) 19 elif c == ',' or c == ']': 20 # 把刚才遇到的数字append进去 21 if is_num: 22 cur_list = stack.pop() 23 cur_list.add(NestedInteger(sign * num)) 24 stack.append(cur_list) 25 num, sign, is_num = 0, 1, False 26 27 # 此时为嵌套列表 28 if c == ']' and len(stack) > 1: 29 cur_list = stack.pop() 30 stack[-1].add(cur_list) 31 32 return stack[0]
一般来说,这种差评如潮的题目,又可能不是题目难,而是题目描述不清楚,对人有误导。本题似乎就存在这个问题。