/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
* // Constructor initializes an empty nested list.
* public NestedInteger();
*
* // Constructor initializes a single integer.
* public NestedInteger(int value);
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // Set this NestedInteger to hold a single integer.
* public void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* public void add(NestedInteger ni);
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
public class Solution {
public NestedInteger deserialize(String s) {
if (s.isEmpty()) {
return null;
}
if (s.charAt(0) != '[') {
return new NestedInteger(Integer.valueOf(s));
}
Stack<NestedInteger> stack = new Stack<NestedInteger>();
NestedInteger curr = null;
int l = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '[') {
if (curr != null) {
stack.push(curr);
}
curr = new NestedInteger();
l = i + 1;
}
else if (s.charAt(i) == ']') {
String val = s.substring(l , i);
if (!val.isEmpty()) {
curr.add(new NestedInteger(Integer.valueOf(val)));
}
if (!stack.isEmpty()) {
NestedInteger pop = stack.pop();
pop.add(curr);
curr = pop;
}
l = i + 1;
}
else if (s.charAt(i) == ',') {
if (s.charAt(i - 1) != ']') {
String num = s.substring(l, i);
curr.add(new NestedInteger(Integer.valueOf(num)));
}
l = i + 1;
}
}
return curr;
}
}[leetCode刷题笔记]385. Mini Parser
最新推荐文章于 2022-10-10 17:08:54 发布
本文介绍了一个用于处理NestedInteger对象的解决方案,该对象可以包含整数或嵌套的NestedInteger列表。通过实现一个名为deserialize的方法,将字符串转换为NestedInteger对象,支持解析包含嵌套列表和整数的JSON风格字符串。
2496

被折叠的 条评论
为什么被折叠?



