原題地址: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()