zoukankan      html  css  js  c++  java
  • [LeetCode] 150. 逆波兰表达式求值

    题目链接 : https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

    题目描述:

    根据逆波兰表示法,求表达式的值。

    有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

    说明:

    • 整数除法只保留整数部分。
    • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

    示例:

    示例 1:

    输入: ["2", "1", "+", "3", "*"]
    输出: 9
    解释: ((2 + 1) * 3) = 9
    

    示例 2:

    输入: ["4", "13", "5", "/", "+"]
    输出: 6
    解释: (4 + (13 / 5)) = 6
    

    思路:

    用栈就可以了, 遇到数字压入栈, 遇到操作符,弹出栈顶两个元素操作就可以了!

    class Solution:
        def evalRPN(self, tokens: List[str]) -> int:
            stack = []
            for t in tokens:
                if t in {"+", "-", "/", "*"}:
                    tmp1 = stack.pop()
                    tmp2 = stack.pop()
                    stack.append(str(int(eval(tmp2+t+tmp1))))
                else:
                    stack.append(t)
            return stack.pop()     
    

    执行速度太慢, 可能用了eval原因,换一种写法,大家可以借鉴这样写法, 看起来很舒服!

    class Solution:
        def evalRPN(self, tokens: List[str]) -> int:
            stack = []
            plus = lambda a, b : b + a
            sub = lambda a, b: b - a
            mul = lambda a, b: b * a
            div = lambda a, b: int(b / a)
            opt = {
                "+": plus,
                "-": sub,
                "*": mul,
                "/": div
            }
            for t in tokens:
                if t in opt:
                    stack.append(opt[t](stack.pop(), stack.pop()))
                else:
                    stack.append(int(t))
            return stack.pop()
    

    java

    class Solution {
        public int evalRPN(String[] tokens) {
            Deque<Integer> stack = new LinkedList<>();
            for (String s : tokens) {
                if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
                    int right = stack.pop();
                    int left = stack.pop();
                    if (s.equals("+")) stack.push(left + right);
                    if (s.equals("-")) stack.push(left - right);
                    if (s.equals("*")) stack.push(left * right);
                    if (s.equals("/")) stack.push(left / right);
                } else {
                    stack.push(Integer.valueOf(s));
                }
            }
            return stack.pop();
        }
    }
    
  • 相关阅读:
    android中requestFocus
    @SuppressLint("NewApi")和@TargetApi()的区别
    Gradle基础
    Gradle build-info.xml not found for module app.Please make sure that you are using gradle plugin '2.0.0-alpha4' or higher.
    Duplicate files copied in APK META-INF/DEPENDENCIES
    解决Gradle DSL method not found: ‘android()’
    SSL peer shut down incorrectly
    如何测试远端TCP和UDP端口是否开放
    方法总比困难多
    图灵简传
  • 原文地址:https://www.cnblogs.com/powercai/p/11272695.html
Copyright © 2011-2022 走看看