• Evaluate Reverse Polish Notation——LeetCode


    Evaluate the value of an arithmetic expression in Reverse Polish Notation.

    Valid operators are +-*/. Each operand may be an integer or another expression.

    Some examples:

      ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
      ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

    题目大意:给定一个String数组,数据是一个后缀表达式,求这个表达式的值。

    解题思路:用栈来保存操作数即可,遇到数就入栈,遇到操作符就从栈里取出两个元素运算然后入栈即可,最后栈里只剩一个元素就是结果。这个不带括号还容易一点,直接上代码。

      static Map<String, Integer> op = new HashMap<>();
    
        static {
            op.put("+", 1);
            op.put("-", 2);
            op.put("*", 3);
            op.put("/", 4);
        }
    
        public int evalRPN(String[] tokens) {
            if (tokens == null || tokens.length == 0) {
                return 0;
            }
            Stack<Integer> nums = new Stack<>();
            for (String s : tokens) {
                if (op.get(s) != null) {
                    int fa = nums.pop();
                    int fb = nums.pop();
                    if (op.get(s) == 1) {
                        nums.push(fb + fa);
                    } else if (op.get(s) == 2) {
                        nums.push(fb - fa);
                    } else if (op.get(s) == 3) {
                        nums.push(fb * fa);
                    } else {
                        nums.push(fb / fa);
                    }
                } else {
                    nums.push(Integer.valueOf(s));
                }
            }
            return nums.peek();
        }
  • 相关阅读:
    gitlab 重置密码
    _string 灵活查询
    删除前面,删除后面
    HTTPS
    PHP正则匹配价格
    PHP LUHN算法验证银行卡
    PHP 与操作判断奇偶
    PHP与Cookie
    检查字符串是否存在
    php密码正则匹配
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4480605.html
Copyright © 2020-2023  润新知