Leetcode 逆波兰表达式求值
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String token : tokens) {
if(isOperator(token)) {
int b = stack.pop();
int a = stack.pop();
stack.push(calculate(a, b, token));
} else {
stack.push(Integer.parseInt(token));// 将字符转换为整数
}
}
return stack.pop();
}
private int calculate(int a, int b, String operator) {
switch(operator) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
private boolean isOperator(String token) {
return "+-*/".contains(token);
}
}