# This solution assumes NestedInteger class is provided by Leetcode.
class Solution:
def deserialize(self, s: str) -> 'NestedInteger':
if not s:
return None
if s[0] != '[':
return NestedInteger(int(s))
stack = []
num = ''
for i, ch in enumerate(s):
if ch == '[':
stack.append(NestedInteger())
elif ch == ']':
if num:
stack[-1].add(NestedInteger(int(num)))
num = ''
if len(stack) > 1:
ni = stack.pop()
stack[-1].add(ni)
elif ch == ',':
if num:
stack[-1].add(NestedInteger(int(num)))
num = ''
else:
num += ch
return stack[0]
// This solution assumes NestedInteger class is provided by Leetcode.
class Solution {
public:
NestedInteger deserialize(string s) {
if (s.empty()) return NestedInteger();
if (s[0] != '[') return NestedInteger(stoi(s));
stack<NestedInteger> st;
int num = 0, sign = 1;
bool hasNum = false;
for (int i = 0; i < s.size(); ++i) {
char c = s[i];
if (c == '[') {
st.push(NestedInteger());
} else if (c == '-' || isdigit(c)) {
sign = (c == '-') ? -1 : 1;
int j = i;
if (c == '-') ++j;
num = 0;
while (j < s.size() && isdigit(s[j])) {
num = num * 10 + (s[j] - '0');
++j;
}
num *= sign;
st.top().add(NestedInteger(num));
i = j - 1;
} else if (c == ']') {
if (st.size() > 1) {
NestedInteger ni = st.top(); st.pop();
st.top().add(ni);
}
}
}
return st.top();
}
};
// This solution assumes NestedInteger class is provided by Leetcode.
public class Solution {
public NestedInteger deserialize(String s) {
if (s.isEmpty()) return null;
if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s));
Stack<NestedInteger> stack = new Stack<>();
int num = 0, sign = 1;
boolean hasNum = false;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (c == '[') {
stack.push(new NestedInteger());
} else if (c == '-' || Character.isDigit(c)) {
sign = (c == '-') ? -1 : 1;
int j = i;
if (c == '-') ++j;
num = 0;
while (j < s.length() && Character.isDigit(s.charAt(j))) {
num = num * 10 + (s.charAt(j) - '0');
++j;
}
num *= sign;
stack.peek().add(new NestedInteger(num));
i = j - 1;
} else if (c == ']') {
if (stack.size() > 1) {
NestedInteger ni = stack.pop();
stack.peek().add(ni);
}
}
}
return stack.peek();
}
}
// This solution assumes NestedInteger class is provided by Leetcode.
var deserialize = function(s) {
if (s[0] !== '[') return new NestedInteger(parseInt(s));
let stack = [];
let num = '';
for (let i = 0; i < s.length; ++i) {
let ch = s[i];
if (ch === '[') {
stack.push(new NestedInteger());
} else if (ch === ']') {
if (num.length) {
stack[stack.length - 1].add(new NestedInteger(parseInt(num)));
num = '';
}
if (stack.length > 1) {
let ni = stack.pop();
stack[stack.length - 1].add(ni);
}
} else if (ch === ',') {
if (num.length) {
stack[stack.length - 1].add(new NestedInteger(parseInt(num)));
num = '';
}
} else {
num += ch;
}
}
return stack[0];
};
s
can represent:
"123"
)"[123,[456,[789]]]"
)NestedInteger
) that can represent either a single integer or a nested list of integers.
s
is always valid and well-formed.NestedInteger
objects as needed.NestedInteger
interface is provided; you only need to implement the parsing logic.'['
signals the start of a new nested list, and every ']'
signals the end of one.NestedInteger
structure as we parse, keeping track of context as we enter and exit nested lists.
'['
, it is just a single integer. Return a NestedInteger
holding that value.'['
, push a new empty NestedInteger
(representing a list) onto the stack.'-'
), accumulate them into a number string.','
or ']'
, if we have accumulated digits, convert them to an integer, wrap them in a NestedInteger
, and add to the current top list.']'
, pop the top NestedInteger
from the stack, and add it to the next top (its parent list), unless it's the outermost list.NestedInteger
structure at its bottom.'['
and ']'
naturally maps to push and pop.','
or ']'
) is encountered, which ensures we handle multi-digit and negative numbers correctly."[123,[456,[789]]]"
:
'['
, push new list onto stack.'1'
, '2'
, '3'
→ accumulate num = "123"
.','
, convert "123"
to integer, add NestedInteger(123)
to top list.'['
, push new list onto stack.'4'
, '5'
, '6'
→ accumulate num = "456"
.','
, convert "456"
to integer, add NestedInteger(456)
to top list.'['
, push new list onto stack.'7'
, '8'
, '9'
→ accumulate num = "789"
.']'
, convert "789"
to integer, add NestedInteger(789)
to top list. Pop this list, add it to its parent.']'
, pop current list, add to parent.']'
, parsing is done.NestedInteger
list containing 123
and another list which contains 456
and another list containing 789
.
NestedInteger
structure. This approach ensures we handle all valid inputs, including single integers and arbitrarily nested lists, with optimal O(n) time and space complexity.