Problem: 150. 逆波兰表达式求值
思路
经典的一道 使用栈来实现逆波兰表达式的应用
需要将中间结果再次压栈
Code
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
//利用栈实现逆波兰表达式
if (tokens.length == 0) {
return 0;
}
for (String token : tokens) {
if (!"+".equals(token) && !"-".equals(token) && !"*".equals(token) && !"/".equals(token)) {
stack.push(token);
}else {
String pop1 = stack.pop();
int b = Integer.parseInt(pop1);
String pop2 = stack.pop();
int a = Integer.parseInt(pop2);
int num = 0;
if ("+".equals(token)){
num=a + b;
} else if ("-".equals(token)) {
num = a - b;
} else if ("*".equals(token)) {
num = a * b;
} else {
num = a / b;
}
stack.push(String.valueOf(num));
}
}
return Integer.parseInt(stack.peek());
}
}