Apparently using stack is a good idea. If we switch the four cases, the branches are too many. So we can use the operator module to simplify the code.
Note the last 'int' is necessary because the result should be type of int.
Solution:
# T:O(n) S:O(n) import operator class Solution: # @param tokens, a list of string # @return an integer def evalRPN(self, tokens): numerals, operators = [], \ {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} for token in tokens: if token not in operators: numerals.append(int(token)) else: y, x = numerals.pop(), numerals.pop() numerals.append(int(operators[token](x * 1.0, y))) return numerals.pop()Run Time: 80 ms
No comments:
Post a Comment