Question
Solution
分析:用NI(count,list)来表示NestedInteger,则解析字符串[123,[456,[789]]]
过程如下:
# 首先将字符串转化为字符数组,遍历每个字符
[ 压栈操作 NI(0, null)
123 给栈顶元素设置值 NI(0, NI(123))
, 不处理
[ 压栈操作 NI(0, NI(123)) | NI(0, null)
456 给栈顶元素设置值 NI(0, NI(123)) | NI(0, 456)
, 不处理
[ 压栈操作 NI(0, NI(123)) | NI(0, NI(456)) | NI(0, null)
789 给栈顶元素设置值 NI(0, NI(123)) | NI(0, NI(456)) | NI(0, NI(789))
] 出栈并将出栈后的元素添加到栈顶元素NI(0, NI(123)) | NI(0, [NI(456),NI(0, NI(789))])
] 出栈并将出栈后的元素添加到栈顶元素NI(0, [NI(123), NI(0, [NI(456), NI(0, NI(789))])])
] 不做处理
# 栈中最后一个元素就是返回结果
Java实现:
public NestedInteger deserialize(String s) {
if (!s.startsWith("[")) return new NestedInteger(Integer.parseInt(s));
Stack<NestedInteger> stack = new Stack<>();
// 123,[456,[789]]
char[] arr = s.toCharArray();
for (int i = 0; i < arr.length; i++) {
char ch = arr[i];
if (ch == '[') {
stack.push(new NestedInteger());
} else if (ch == ']' & stack.size() > 1) {
NestedInteger pop = stack.pop();
stack.peek().add(pop);
} else if (Character.isDigit(ch) || ch == '-') {
boolean pos = true;
if (ch == '-') {
pos = false;
i++;
}
int num = 0;
while (i < arr.length && Character.isDigit(arr[i])) {
num *= 10;
num += arr[i++] - '0';
}
i--;
stack.peek().add(new NestedInteger(pos ? num : -num));
}
}
return stack.pop();
}
Reference
原文地址:https://www.cnblogs.com/okokabcd/p/9175184.html
时间: 2024-10-17 12:06:06