150. (逆波兰表达式( stack))

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


class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for ch in tokens:
            if ch not in set(["+",'-',"*",'/']):
                stack.append(int(ch))
            else:
                a = stack.pop()
                b = stack.pop()
                if ch == '+':
                    stack.append(a+b)
                elif ch == '-':
                    stack.append(b-a)
                elif ch == '*':
                    stack.append(a*b)
                elif ch == '/':
                    stack.append(int(b/a))
            #print (stack)
        return stack[-1]

 

 

 

posted @ 2018-02-25 16:33  乐乐章  阅读(144)  评论(0编辑  收藏  举报