题目
思路
- 直接用栈,整两个栈,最后倒一下就可以。
代码
public int calculate(String s) {
Stack<Integer> int_stack = new Stack<>();
Stack<Character> char_stack = new Stack<>();
for(int i=0;i<s.length();i++){
Character c= s.charAt(i);
if(c==' ') continue;
else if(c>='0' && c<='9'){
StringBuilder sb = new StringBuilder();
sb.append(c);
while((i+1)<s.length() && s.charAt(i+1)>='0' && s.charAt(i+1)<='9'){
sb.append(s.charAt(i+1));
i++;
}
if(char_stack.size()>0 && (char_stack.peek()=='*' || char_stack.peek()=='/')){
int num1 = Integer.valueOf(sb.toString());
int num2 = int_stack.pop();
char op = char_stack.pop();
int ans=0;
if(op=='*') ans = num1*num2;
if(op=='/') ans = num2/num1;
int_stack.push(ans);
}else {
int_stack.push(Integer.valueOf(sb.toString()));
}
}
else if(c=='+' || c=='-' || c=='/' || c=='*'){
char_stack.push(c);
}
}
Stack<Integer> int_stack_1 = new Stack<>();
Stack<Character> char_stack_1 = new Stack<>();
while (!int_stack.empty()) int_stack_1.push(int_stack.pop());
while (!char_stack.empty()) char_stack_1.push(char_stack.pop());
while(!char_stack_1.empty()){
Character c= char_stack_1.pop();
int num1 = int_stack_1.pop();
int num2 = int_stack_1.pop();
if(c=='+') int_stack_1.push(num1+num2);
if(c=='-') int_stack_1.push(num1-num2);
}
return int_stack_1.peek();
}