LeetCode 224. 基本计算器
计算器得简单题,本来想用后缀+栈来解决,但是没想到只涉及加减和括号可以直接用括号展开得思想进行解决;
主要方法是使用栈来记录当前整个括号内的值;
对字符串内的符号进行记录,为括号展开作准备;
例如:-(2+1)
记录负号之后,遇到左括号直接压栈,此时取栈顶符号进行+,-号判断时,可以达到相反的判断逻辑,遇到右括号直接弹栈,避免对括号外围得影响;
算是括号展开的一种取巧得方式;
class Solution {
public:
int calculate(string s) {
int index = 0;
int ret = 0;
stack<bool>sign;
sign.push(true);
bool sg = true;
while (index < s.size()) {
if (s[index] == '+') {
sg = sign.top();
index++;
}
else if (s[index] == '-') {
sg = !sign.top();
index++;
}
else if (s[index] == '(') {
sign.push(sg);
index++;
}
else if (s[index] == ')') {
sign.pop();
index++;
}
else if (s[index] >= '0' && s[index] <= '9') {
int cnt = 0;
while (s[index] >= '0' && s[index] <= '9') {
cnt = cnt * 10 + (s[index++] - '0');
}
if (sg) {
ret += cnt;
}
else {
ret -= cnt;
}
}
else
index++;
}
return ret;
}
};

浙公网安备 33010602011771号