思路:利用辅助栈,并用preSign记录运算符号
public int calculate(String s){
Stack<Integer> stack=new Stack<>();
int num=0;
char preSign='+';
for(int i=0;i<s.length();i++){
if(Character.isDigit(s.charAt(i))){
num=num*10+s.charAt(i)-'0';
}
if(!Character.isDigit(s.charAt(i))&&s.charAt(i)!=' '||i==s.length()-1){
if(preSign=='+') stack.push(num);
else if(preSign=='-') stack.push(-num);
else if(preSign=='*') stack.push(stack.pop()*num);
else if(preSign=='/') stack.push(stack.pop()/num);
preSign=s.charAt(i);
num=0;
}
}
int res=0;
while(!stack.isEmpty()){
res+=stack.pop();
}
return res;
}