用栈计算逆波兰表达式的基本思路是:按顺序遍历整个表达式,
若遇到操作数(假设都是二元运算符)则入栈;若遇到操作符(+ - * /)
连续弹出两个操作数并执行相应的运算,然后将其运算结果入栈。
重复以上过程,直到表达式遍历完,栈内只剩下一个操作数时,那
就是最终的运算结果,弹出打印即可。
import java.util.Stack;public class Solution17 {public static int evaluateRPN(String[] tokens){Stack<Integer> stack = new Stack<>();for(String token : tokens){if(isOperator(token)){int b=stack.pop();int a=stack.pop();int result=applyOpeartor(token,a,b);stack.push(result);}else{stack.push(Integer.parseInt(token));}}return stack.pop();}private static boolean isOperator(String token){return "+-*/".contains(token);}private static int applyOpeartor(String operator, int a, int b){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);}}public static void main(String[] args) {String[] tokens = {"8", "2", "+", "2","*"};int result = evaluateRPN(tokens);System.out.println(result);}
}