题目
类型:双栈
难度:中等
class Solution {
public:
int calculate(string s) {
//yxc 2020.3.29
//乘除法先算
stack<char> op;
stack<int> num;
s +="+0"; //处理边界
int n = s.size();
for(int i = 0; i < n; i++){
if(s[i]==' ') continue;
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
op.push(s[i]);
}else{
//空格不可能在数字中间
int t = 0;
while(i < n && isdigit(s[i])) t = t*10-'0'+s[i++];
i--;
num.push(t);
if(!op.empty()){
if(op.top() == '*' || op.top()=='/'){
int y = num.top();num.pop();
int x = num.top();num.pop();
if(op.top()=='*') num.push(x*y);
else num.push(x/y);
op.pop(); //符号栈为乘除法先算
}else if(op.size() >= 2){ //加减法有两个 先算栈底这个 加减最多两个
int z = num.top();num.pop();
int y = num.top();num.pop();
int x = num.top(); num.pop();
char op1 = op.top(); op.pop();
char op2 = op.top(); op.pop();
if(op2 == '+') num.push(x+y);
else num.push(x-y);
num.push(z);
op.push(op1);
}
}
}
}
num.pop();
return num.top();
}
};