zoukankan      html  css  js  c++  java
  • [leetcode]Evaluate Reverse Polish Notation @ Python

    原题地址:https://oj.leetcode.com/problems/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.

    Some examples:

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

    解题思路:这道题是经典的逆波兰式求值。具体思路是:开辟一个空栈,遇到数字压栈,遇到运算符弹出栈中的两个数进行运算,并将运算结果压栈,最后栈中只剩下一个数时,就是所求结果。这里需要注意的一点是python中的'/'除法和c语言不太一样。在python中,(-1)/2=-1,而在c语言中,(-1)/2=0。也就是c语言中,除法是向零取整,即舍弃小数点后的数。而在python中,是向下取整的。而这道题的oj是默认的c语言中的语法,所以需要在遇到'/'的时候注意一下。

    代码:

    class Solution:
        # @param tokens, a list of string
        # @return an integer
        def evalRPN(self, tokens):
            stack = []
            for i in range(0,len(tokens)):
                if tokens[i] != '+' and tokens[i] != '-' and tokens[i] != '*' and tokens[i] != '/':
                    stack.append(int(tokens[i]))
                else:
                    a = stack.pop()
                    b = stack.pop()
                    if tokens[i] == '+':
                        stack.append(a+b)
                    if tokens[i] == '-':
                        stack.append(b-a)
                    if tokens[i] == '*':
                        stack.append(a*b)
                    if tokens[i] == '/':
                        if a*b < 0:
                            stack.append(-((-b)/a))
                        else:
                            stack.append(b/a)
            return stack.pop()
  • 相关阅读:
    P1019 单词接龙
    最小生成树模板题POJ
    区间DP
    牛客多校第三场-A-PACM Team-多维背包的01变种
    洛谷P1004 方格取数-四维DP
    牛客多校第二场A run(基础DP)
    P1494 [国家集训队]小Z的袜子(莫队)
    洛谷:过河卒
    Codeforces Round #486 (Div. 3)-B. Substrings Sort
    判断的值是否为空
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3760530.html
Copyright © 2011-2022 走看看