利用栈的思想,遇到数字就push进去,遇到运算符号,将栈顶的两个元素拿来运算得到对应的值,pop掉两个运算的值,push进得到的值。 注意: leetcode内置的int函数和我们平时的int函数有区别,所以在进行除法求值的时候我们需要修改一下,然后才能得到正确的值,细节可以看代码。
具体代码如下:
class Solution(object): def evalRPN(self, tokens): """ :type tokens: List[str] :rtype: int """ #stack data = [] ops = ['-', '+', '*', '/'] for char in tokens: if char not in ops: data.append(int(char)) else: first = data[-2] second = data[-1] data = data[:-2] if char == '+': data.append(first + second) elif char == '-': data.append(first - second) elif char == '*': data.append(first * second) elif char == '/': if first % second == 0: data.append(first/second) elif first * second > 0: data.append(int(first/second)) else: data.append(int(first/second) + 1) return data[0]