- 使用双栈计算表达式结果(存符号、数字)
- 空格: 直接忽略
- ( : 入栈
- ) : 计算结果直到遇到 (
- 数字: 累计记录当前数字
- 栈顶运算符优先级高于/同等 当前运算符,就一直弹出
- 注意事项
- “-2 + 1”,先在nums栈加上0,防止第一个就是 "-"
class Solution {
public:
void init(string &s) {
int pos = s.find("(-");
while(pos != -1) {
s = s.replace(pos, 2, "(0-");
pos = s.find("(-");
}
}
Solution() {
priority_v['+'] = 1;
priority_v['-'] = 1;
priority_v['*'] = 2;
priority_v['/'] = 2;
}
inline void cal() {
double n2 = nums.top(); nums.pop();
double n1 = nums.top(); nums.pop();
char ch = ops.top();
if(ch == '+') {
nums.push(n1 + n2);
} else if(ch == '-') {
nums.push(n1 - n2);
} else if(ch == '*') {
nums.push(n1 * n2);
} else {
nums.push(n1 / n2);
}
ops.pop();
return;
}
double calculate(string &s) {
nums.push(0.0);
LL tmp = 0;
int f = 0;
for(const auto &ch : s) {
if(ch >= '0' && ch <= '9') {
tmp = tmp * 10LL + static_cast<int>(ch - '0');
f = 1;
} else {
if(ch == ' ') continue;
if(f) nums.push(tmp);
tmp = 0;
f = 0;
if(ch == '(') {
ops.push(ch);
} else if(ch == ')') {
while(!ops.empty() && ops.top() != '(') {
cal();
}
ops.pop();
} else {
while(!ops.empty() && priority_v[ops.top()] >= priority_v[ch]) {
cal();
}
ops.push(ch);
}
}
}
if(f) nums.push(tmp);
while(!ops.empty()) {
cal();
}
return nums.top();
}
private:
stack<double>nums;
stack<char>ops;
map<char,int>priority_v;
};