zoukankan      html  css  js  c++  java
  • 150. Evaluate Reverse Polish Notation

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

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

    Note:

    • Division between two integers should truncate toward zero.
    • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

    Example 1:

    Input: ["2", "1", "+", "3", "*"]
    Output: 9
    Explanation: ((2 + 1) * 3) = 9
    

    Example 2:

    Input: ["4", "13", "5", "/", "+"]
    Output: 6
    Explanation: (4 + (13 / 5)) = 6
    

    Example 3:

    Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
    Output: 22
    Explanation: 
      ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
    = ((10 * (6 / (12 * -11))) + 17) + 5
    = ((10 * (6 / -132)) + 17) + 5
    = ((10 * 0) + 17) + 5
    = (0 + 17) + 5
    = 17 + 5
    = 22
    class Solution {
        public int evalRPN(String[] tokens) {
            Stack<String> s = new Stack<>();
            for (String token : tokens) {
                if (!isOperator(token)) {
                    s.push(token);
                } else {
                    int y = Integer.parseInt(s.pop());
                    int x = Integer.parseInt(s.pop());
                    switch (token.charAt(0)) {
                        case '+': x += y; break;
                        case '-': x -= y; break;
                        case '*': x *= y; break;
                        default: x /= y;
                    }
                    s.push(String.valueOf(x));
                }
            }
            return Integer.parseInt(s.peek());
        }
        private static boolean isOperator(final String op) {
            return op.length() == 1 && OPS.indexOf(op) != -1;
        }
        private static String OPS = new String("+-*/");
    }

    想起了宝拉老哥,用stack解决,遇到数字就push,遇到标点就pop两个数字,后pop的是被除数,运算完成后再push回stack。

    最后peek顶端的。

    检查是不是标点符号有点东西,用index来判断。

  • 相关阅读:
    IEEE754二进制浮点数算术标准
    符号三角形代码勘误
    最近点对问题
    【Unsolved】线性时间选择算法的复杂度证明
    解决mosh: Nothing received from server on UDP port 60001 环境: centos7.1
    半导体测试基础
    python进程------multiprocessing包
    python线程------queue、生产者和消费者模式
    pyhon——线程同步条件(event)
    os 模块
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10569298.html
Copyright © 2011-2022 走看看