zoukankan      html  css  js  c++  java
  • 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();
        }
  • 相关阅读:
    架构设计的UML图形思考
    SymmetricDS文档翻译--【Chapter 3. 具体配置(Configuration)[section C]】
    LeetCodeOJ. String to Integer (atoi)
    jquery05 继承
    jquery 04
    jquery constructor(null)
    jquery js解析函数、函数直接调用
    jquery init 关系
    jquery constructor
    jQuery03
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4480605.html
Copyright © 2011-2022 走看看