逆波兰表达式求值,使用Java栈实现

    技术2022-07-10  98

    import java.util.Stack; /** * 逆波兰表达式求值 * 整数除法只保留整数部分。 * 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。 * 示例 1: * 输入: ["2", "1", "+", "3", "*"] * 输出: 9 * 解释: 该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9 * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation */ public class ReversePolishNotation { public static int evlRPN(String[] tokens){ Stack<Integer> stack = new Stack<>(); for(int i = 0; i < tokens.length; i ++){ if("+".equals(tokens[i])){ stack.push(stack.pop() + stack.pop()); }else if("-".equals(tokens[i])){ Integer num1 = stack.pop(); Integer num2 = stack.pop(); stack.push(num2 - num1); }else if("*".equals(tokens[i])){ Integer num1 = stack.pop(); Integer num2 = stack.pop(); stack.push(num2 * num1); }else if("/".equals(tokens[i])){ Integer num1 = stack.pop(); Integer num2 = stack.pop(); stack.push(num2 / num1); }else { stack.push(Integer.valueOf(tokens[i])); } } return stack.pop(); } public static void main(String[] args){ //预期结果 9 6 22 String[] tokens = {"2", "1", "+", "3", "*"}; String[] tokens1 = {"4", "13", "5", "/", "+"}; String[] tokens2 = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}; System.out.println(evlRPN(tokens)); System.out.println(evlRPN(tokens1)); System.out.println(evlRPN(tokens2)); //实际结果 9 6 22 } }
    Processed: 0.015, SQL: 9