题目
给定一个字符串 s 表示一个整数嵌套列表,实现一个解析它的语法分析器并返回解析的结果 NestedInteger 。
列表中的每个元素只可能是整数或整数嵌套列表
示例
输入:s = “324”,
输出:324
解释:你应该返回一个 NestedInteger 对象,其中只包含整数值 324。
输入:s = “[123,[456,[789]]]”,
输出:[123,[456,[789]]]
解释:返回一个 NestedInteger 对象包含一个有两个元素的嵌套列表:
- 一个 integer 包含值 123
- 一个包含两个元素的嵌套列表:
i. 一个 integer 包含值 456
ii. 一个包含一个元素的嵌套列表
a. 一个 integer 包含值 789
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/mini-parser
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:栈

// 这里用一个例子说明情况,首先需要明确,栈中,列表中,添加的都是 NestedInteger 对象
// s = "[-2,[234, 678]]" 遍历到第一个 ']' 的时候,此时栈对应的状态为 {空,SIGN, -2, 空,SIGN, 234, 678}
// 现在遇到了第一个 ']' ,那么我们需要将连续出栈 的 678,234 加到list,直到遇到SIGN, 也就是 list = [678,234] 然后逆序加到 空 中,使用add
// 则此时是:{空,SIGN, -2, [234, 678]},下一步遇到了第二个 ']',则此时也是连续出栈,此时的 list = [[234, 678], -2]
// 加到最开始的 空 中,
// {[-2,[234,678]]} ; 然后 return deque.peekLast(); 就是 [-2,[234,678]]
Java实现
class Solution {
//特殊标记,表示'['
static final NestedInteger SIGN = new NestedInteger(0);
public NestedInteger deserialize(String s) {
if (s.charAt(0) != '[') return new NestedInteger(Integer.parseInt(s));
Deque<NestedInteger> q = new LinkedList<>();
char[] cs = s.toCharArray();
int n = cs.length, i = 0;
while (i < n) {
if (cs[i] == ',' && ++i >= 0) continue; //如果是',' 直接跳过
else if (cs[i] == '-' || (cs[i] >= '0' && cs[i] <= '9')) { //满足可以解析为整数的条件: 负号开始,或者 0-9的数字
int j = cs[i] == '-' ? i + 1 : i; //真实的不考虑正负的数字从哪儿开始
int num = 0;
while (j < n && (cs[j] >= '0' && cs[j] <= '9')) {
num = num * 10 + (cs[j] - '0');
j++;
}
q.addLast(new NestedInteger(cs[i] == '-' ? -num : num));
i = j;
} else if (cs[i] == '[') {
//这个空的是为了遇到 ’]' 的时候,反过来往里面添加。
//请注意,调用 NestedInteger.add() 的时候会生成列表
q.addLast(new NestedInteger());
//这个 SIGN 是为了说明,这里是一个 '['
q.addLast(SIGN);
i++;
} else { //遇到']'时
List<NestedInteger> list = new ArrayList<>();
while (!q.isEmpty()) {
NestedInteger poll = q.pollLast();
if (poll == SIGN) break;
list.add(poll);
}
//需要逆序添加
//加入到栈的 空NestedInteger 对象当中
for (int j = list.size() - 1; j >= 0; j--) {
q.peekLast().add(list.get(j));
}
i++;
}
}
return q.peekLast();
}
}

该博客介绍了一种方法来解析表示整数嵌套列表的字符串,通过使用栈来处理嵌套的'[', ']'字符。在遍历字符串时,遇到数字则转化为NestedInteger对象,遇到'['则压入栈中,遇到']'则连续出栈并构建嵌套列表。最终返回栈顶的NestedInteger对象作为解析结果。

5781

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



