[LeetCode]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
Solution: Use Stack (mostly for Parentheses processing )
Running Time: O(n)
class Solution:
    # @param tokens, a list of string
    # @return an integer
    def isInt(self, s):
        try:
            int(s)
            return True
        except ValueError:
            return False
            
    
    def evalRPN(self, tokens):
        tempStack = []
        for element in tokens:
            if self.isInt(element):
                tempStack.append(int(element))
            else:
                b = tempStack.pop()
                a = tempStack.pop()
                if element == '+':
                    c = a + b
                elif element == '-':
                    c = a - b
                elif element == '*':
                    c = a * b
                elif element == '/':
                    try:
                        c = int(float(a) / b)#in python -6/132 = -1, but the answer here require 0 as result
                    except ValueError:
                        print "Error: divisor cannot be 0."
                tempStack.append(c)
        return int(tempStack.pop())

对于括号处理,通常使用Stack作为容器。



你可能感兴趣的:(LeetCode,python,stack)