思路:此题不考虑括号和负数情况,单纯使用栈即可解决。注意的是数字可能是多位数需要保留完整的num, 保留数字的前缀符号,当碰到加号,存进去;当碰到减号,存相反数进去;当碰到乘除就弹出栈顶元素运算后把结果存进去;最后相加就是结果
class Solution {
public int calculate(String s) {
Deque stack = new ArrayDeque();
char preSign = '+';
int num = 0;
int n = s.length();
for (int i = 0; i < n; ++i) {
char c = s.charAt(i);
if(c >= '0' && c <= '9'){
num = num*10 + c - '0';
}
if((!(c >= '0' && c <= '9')&&c != ' ') || i==n-1 ){
switch(preSign){
case '+' :
stack.push(num);
break;
case '-' :
stack.push(-num);
break;
case '/':
stack.push(stack.pop()/num);
break;
case '*':
stack.push(stack.pop()*num);
break;
}
preSign = c;
num=0;
}
}
num = 0;
while(!stack.isEmpty()){
num += stack.pop();
}
return num;
}
}
class Solution {
public int evalRPN(String[] tokens) {
Deque stack = new LinkedList<>();
for(int i = 0;i