[LeetCode]题解(python):150-Evaluate Reverse Polish Notation

题目来源:

  https://leetcode.com/problems/evaluate-reverse-polish-notation/


题意分析:

  给定一个数组,用这个数组来表示加减乘除,例如

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

题目思路:

  这里考虑的是栈的使用。如果是数字那么push进栈,如果不是,那么把栈后两个数pop出来,进行相应的操作。要注意的是除法的时候要保证先转化正负一致再进行计算。


代码(python):

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        ans = []
        for i in tokens:
            if i != '/' and i != '*' and i != '+' and i != '-':
                ans.append(int(i))
            else:
                tmp1 = ans.pop()
                tmp2 = ans.pop()
                if i == '/':
                    if tmp1*tmp2 < 0:
                        ans.append(-((-tmp2) // tmp1))
                    else:
                        ans.append(tmp2/tmp1)
                if i == '*':
                    ans.append(tmp2*tmp1)
                if i == '+':
                    ans.append(tmp2 + tmp1)
                if i == '-':
                    ans.append(tmp2 - tmp1)
        return ans[0]
View Code
原文地址:https://www.cnblogs.com/chruny/p/5478203.html