美文网首页
Leetcode-150题:Evaluate Reverse P

Leetcode-150题:Evaluate Reverse P

作者: 八刀一闪 | 来源:发表于2016-09-26 20:50 被阅读177次

题目: 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涉及负数的除法规则和Java等不同,需注意,-1/2在Python中是-1而在Java中是0。

代码:

def evalRPN(self, tokens):
    """
    :type tokens: List[str]
    :rtype: int
    """
    if tokens==None or len(tokens)==0:
        return 0
    num_stack = []
    for c in tokens:
        if c == '+':
            b = num_stack.pop()
            a = num_stack.pop()
            num_stack.append(int(a)+int(b))
        elif c == '-':
            b = num_stack.pop()
            a = num_stack.pop()
            num_stack.append(int(a)-int(b))
        elif c == '*':
            b = num_stack.pop()
            a = num_stack.pop()
            num_stack.append(int(a)*int(b))
        elif c == '/':
            b = num_stack.pop()
            a = num_stack.pop()
            if a/b < 0 and a%b!=0:
                num_stack.append(a/b+1)
            else:
                num_stack.append(a/b)
        else:
            num_stack.append(int(c))
    return num_stack[0]

相关文章

网友评论

      本文标题:Leetcode-150题:Evaluate Reverse P

      本文链接:https://www.haomeiwen.com/subject/dggqyttx.html