Mini Parser
3 times the downvotes. Make it very quick.
The task is to deserialize a string that represents a nested integer structure. The NestedInteger class provides a structure to build this nested integer object. The given string can represent either a single integer or a list of integers, which may also contain other lists.
Here’s the code to deserialize the given string into a NestedInteger object:
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
37
38
39
40
| class Solution:
def deserialize(self, s: str) -> NestedInteger:
if not s:
return None
# If s represents an integer, return a NestedInteger with that value.
if s[0] != '[':
return NestedInteger(int(s))
# Initialize stack to parse nested structures.
stack = []
current_num = ""
current_list = None
for char in s:
if char == '[':
# Start a new list, push the current list onto the stack.
if current_list is not None:
stack.append(current_list)
current_list = NestedInteger()
elif char == ']':
# End the current list, add any remaining integer.
if current_num:
current_list.add(NestedInteger(int(current_num)))
current_num = ""
# If there's a parent list on the stack, add the current list to it.
if stack:
parent_list = stack.pop()
parent_list.add(current_list)
current_list = parent_list
elif char == ',':
# Separate elements within a list.
if current_num:
current_list.add(NestedInteger(int(current_num)))
current_num = ""
else:
# Accumulate digits for a single integer.
current_num += char
return current_list if stack == [] else stack[0]
|
The code processes the input string s
character by character, using a stack to keep track of the nested structure. When it encounters a number, it accumulates the digits until it reaches a comma or closing bracket, then creates a NestedInteger for that number. When it encounters brackets, it starts or ends a nested list, adding it to the current list or the parent list from the stack. By the end of the string, the stack contains the deserialized NestedInteger object.
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
| class Solution:
def deserialize(self, s: str) -> NestedInteger:
if not s:
return None
if s[0] != '[':
return NestedInteger(int(s))
stack = []
current_num = ""
current_list = None
for char in s:
if char == '[':
if current_list is not None:
stack.append(current_list)
current_list = NestedInteger()
elif char == ']':
if current_num:
current_list.add(NestedInteger(int(current_num)))
current_num = ""
if stack:
prev_list = stack.pop()
prev_list.add(current_list)
current_list = prev_list
elif char == ',':
if current_num:
current_list.add(NestedInteger(int(current_num)))
current_num = ""
else:
current_num += char
if current_num:
return NestedInteger(int(current_num))
return current_list
|