public int solve (String s) {
// write code here
Stack<Integer> nums=new Stack<>();
nums.push(0);
Stack<Character> ops=new Stack<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c=='('){
ops.push(c);
}else if(c==')'){
while(ops.peek()!='('){
nums.push(calculate(ops.pop(),nums.pop(),nums.pop()));
}
ops.pop();
}else if(c=='*'||c=='+'||c=='-'){
while(!ops.isEmpty()&&precedence(c)<=precedence(ops.peek())){
nums.push(calculate(ops.pop(),nums.pop(),nums.pop()));
}
ops.push(c);
}else{
int num=0;
while(i<s.length()&&Character.isDigit(s.charAt(i))){
num=num*10+s.charAt(i)-'0';
i++;
}
i--;
nums.push(num);
}
}
while(!ops.isEmpty()){
nums.push(calculate(ops.pop(),nums.pop(),nums.pop()));
}
return nums.pop();
}
private int calculate(char op,int b, int a){
switch(op){
case '+':return a+b;
case '-':return a-b;
case '*': return a*b;
default:return 0;
}
}
private int precedence(char op){//字符的优先级
if(op=='*') return 2;
if(op=='+'||op=='-') return 1;
return 0;
}