题目
类型:栈
解题思路
分析:
要将子串里面的数字转化为int类型按顺序添加到 NestedInteger 实例里面,因此我们就需要遍历字符串s,如果出现 ‘[’,则表示是一个新的 NestedInteger 实例,需要在栈里构造实例,如果出现‘]’ 或 ‘,’,则需要将栈顶的实例对象添加值【就是‘[’和‘]’ 或 ‘,’之间出现的数字转化为int类型添加进去】,重复上述步骤最后需要将其添加入栈顶的 NestedInteger 实例。最后需返回栈顶的实例。
实现步骤:
如果第一个字符不是‘[’则说明他是一个数字直接转化为int类型添加到NestedInteger里即可
若检测到 - 号标志位置 flag = 1
如果是数字直接计算 【计算前记得判断一下flag是否为1】num
检测到左括号向栈里添加对象
如果检测到‘]’ 或 ‘,’且前一个字符是数字,则直接计算前面连续出现的数字,直接添加到栈顶元素的列表即可
将栈里的 NestedInteger(num) 合并为一个对象列表
按照上述逻辑处理完整个 s,最终栈顶元素即是答案。
代码
/**
* // 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 empty list if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
class Solution {
static NestedInteger ph = new NestedInteger(0);
public NestedInteger deserialize(String s) {
Deque<NestedInteger> d = new ArrayDeque<>();
char[] cs = s.toCharArray();
int n = cs.length, i = 0;
while (i < n) {
if (cs[i] == ',' && ++i >= 0) continue;
if (cs[i] == '-' || (cs[i] >= '0' && cs[i] <= '9')) {
int j = cs[i] == '-' ? i + 1 : i, num = 0;
while (j < n && (cs[j] >= '0' && cs[j] <= '9')) num = num * 10 + (cs[j++] - '0');
d.addLast(new NestedInteger(cs[i] == '-' ? -num : num));
i = j;
} else if (cs[i] == '[') {
d.addLast(new NestedInteger());
d.addLast(ph);
i++;
} else {
List<NestedInteger> list = new ArrayList<>();
while (!d.isEmpty()) {
NestedInteger poll = d.pollLast();
if (poll == ph) break;
list.add(poll);
}
for (int j = list.size() - 1; j >= 0; j--) d.peekLast().add(list.get(j));
i++;
}
}
return d.peekLast();
}
}