class Solution {
stack<int> num;
stack<char> op;
//符号优先级
int pri(char c){
switch(c){
case '+':return 1;
case '-':return 1;
case '*':return 2;
case '/':return 2;
case '(':return 3;
default:return -1;
}
}
void cal(){
int b=num.top();
num.pop();
int a=num.top();
num.pop();
switch(op.top()){
case '+':num.push(a+b);break;
case '-':num.push(a-b);break;
case '*':num.push(a*b);break;
case '/':num.push(a/b);break;
}
op.pop();
}
public:
int calculate(string s) {
string str;
for(char c:s){
if(isdigit(c)) str+=c;
else if(c==' ') continue;
else{
if(!str.empty()){
num.push(stoi(str));
str.clear();
}
if(op.empty() || c=='(' || pri(op.top())<pri(c))
op.push(c);
else if(c==')'){
while(op.top()!='(')
cal();
op.pop();//弹出'('
}else{
while(!op.empty() && op.top()!='(' && pri(op.top())>=pri(c))
cal();
op.push(c);
}
}
}
if(!str.empty()) num.push(stoi(str));
while(!op.empty()) cal();
return num.top();
}
};