class Solution {
public:
int calc(int a,int b,char c){
if(c=='+'){
return a+b;
}
if(c=='-')return a-b;
if(c=='*')return a*b;
if(c=='/')return a/b;
return 0;
}
int level(char c){
if(c=='+'||c=='-')return 1;
if(c=='*'||c=='/')return 2;
return 0;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
int solve(string s) {
stack<int> nums;//数字
stack<char> ops;//符号
for(int i=0;i<s.size();i++){
if(isdigit(s[i])){
int num=0;
while(i<s.size()&&isdigit(s[i])){
num=num*10+(s[i]-'0');
i++;
}
nums.push(num);
i--;
}
else if(s[i]=='('){
ops.push('(');
}
else if(s[i]==')'){
while(!ops.empty()&&ops.top()!='('){
int b=nums.top();nums.pop();
int a=nums.top();nums.pop();
char c=ops.top();ops.pop();
nums.push(calc(a,b,c));
}
ops.pop();
}
else{
while(!ops.empty()&&ops.top()!='('&&level(ops.top())>=level(s[i])){
int b=nums.top();nums.pop();
int a=nums.top();nums.pop();
char c=ops.top();ops.pop();
nums.push(calc(a,b,c));
}
ops.push(s[i]);
}
}
while(!ops.empty()){
int b=nums.top();nums.pop();
int a=nums.top();nums.pop();
char c=ops.top();ops.pop();
nums.push(calc(a,b,c));
}
return nums.top();
}
};