150. Evaluate Reverse Polish Notation
# Medium
Solution:
traversal all elements of the list
if it's a number, push to stack
if it's a notation, pop two numbers and compute, then push back to stack
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
i = 0
stack = []
while i < len(tokens):
st = tokens[i]
if st != '+' and st != '-' and st != '*' and st != '/':
stack.append(st)
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if st == '+':
res = num1 + num2
elif st == '-':
res = num1 - num2
elif st == '*':
res = num1 * num2
else:
if num1*num2 < 0:
res = num1*(-1)//num2 * (-1)
else:
res = num1//num2
stack.append(res)
i += 1
return stack.pop()
如果用python则不能用recursive来做,因为python不能传递reference,意味着函数的参数无法成为全局变量,而导致一直在变
Time = , space =
Last updated
Was this helpful?