leetcode-150-逆波兰表达式求值

 题目描述:

方法一:

class Solution:
    def evalRPN(self, t: List[str]) -> int:
        d=[] 
        n=len(t) 
        for i in range(n): 
            if '0'<=t[i][-1]<='9': 
                d+=[t[i]] 
            else: 
                d[-2]=str(int(eval((d[-2]+t[i]+d[-1])))) 
                d.pop() 
        return int(d[0])

 方法二:

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        symbol = ['+', '-', '*', '/'] 
        stack = [] 
        for t in tokens: 
            if t in symbol: 
                stack.append(self.eval(stack.pop(-2), stack.pop(), t)) 
            else: 
                stack.append(int(t)) 
        return stack[-1] 
    def eval(self, x, y, symbol): 
        if symbol == '+': return x + y 
        if symbol == '-': return x - y 
        if symbol == '*': return x * y 
        if symbol == '/': return int(x / y)

猜你喜欢

转载自www.cnblogs.com/oldby/p/11202744.html
今日推荐