385. 迷你语法分析器
题目来源:385. 迷你语法分析器
2022.04.15 每日一题
LeetCode 题解持续更新中GitHub仓库地址 CSDN博客地址
今天的题目就是模拟
使用栈进行模拟
,
:跳过即可;
-
或数字
:将连续段代表数值的字符串取出,创建数值型的 NestedInteger 实例并压入栈中;
[
:创建一个嵌套类型的 NestedInteger 实例并压入栈中,同时为了方便,同步压入一个起「标识」作用的 NestedInteger 对象;
]
:从栈中取出元素,将 [ 和 ] 之间的所有元素添加到 [ 所代指的嵌套 NestedInteger 实例中,然后将 [ 所代指的嵌套 NestedInteger 实例重新放入栈中。
class Solution {
public:
NestedInteger deserialize(string s) {
if (s[0] != '[') {
return NestedInteger(stoi(s));
}
stack<NestedInteger> st;
int num = 0;
bool negative = false;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '-') {
negative = true;
} else if (isdigit(c)) {
num = num * 10 + c - '0';
} else if (c == '[') {
st.emplace(NestedInteger());
} else if (c == ',' || c == ']') {
if (isdigit(s[i - 1])) {
if (negative) {
num *= -1;
}
st.top().add(NestedInteger(num));
}
num = 0;
negative = false;
if (c == ']' && st.size() > 1) {
NestedInteger ni = st.top();
st.pop();
st.top().add(ni);
}
}
}
return st.top();
}
};
class Solution {
public NestedInteger deserialize(String s) {
if (s.charAt(0) != '[') {
return new NestedInteger(Integer.parseInt(s));
}
Deque<NestedInteger> stack = new ArrayDeque<NestedInteger>();
int num = 0;
boolean negative = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '-') {
negative = true;
} else if (Character.isDigit(c)) {
num = num * 10 + c - '0';
} else if (c == '[') {
stack.push(new NestedInteger());
} else if (c == ',' || c == ']') {
if (Character.isDigit(s.charAt(i - 1))) {
if (negative) {
num *= -1;
}
stack.peek().add(new NestedInteger(num));
}
num = 0;
negative = false;
if (c == ']' && stack.size() > 1) {
NestedInteger ni = stack.pop();
stack.peek().add(ni);
}
}
}
return stack.pop();
}
}