题目
解法:stack
题目跟calculator很相似,用stack即可解决
有两个注意点:
- python的isdigit函数对于负数情况需要单独判断
- 这边的负数出发也要注意,//操作是向下取整,int是直接去掉小数部分
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for op in tokens:
# isdigit function does not work for negative number
if op.isdigit() or op[1:].isdigit():
# print(op)
stack.append(int(op))
else:
second_num = stack.pop()
first_num = stack.pop()
if op == '+':
stack.append(first_num+second_num)
elif op == '-':
stack.append(first_num-second_num)
elif op == '*':
stack.append(first_num*second_num)
elif op == '/':
# need to do division first and convert to int, // will do rounds down
# for example -1//2 = -1 rather than 0
# int operation cuts the float part and remain the int part
stack.append(int(first_num / second_num))
# print(stack)
return stack[0]
时间复杂度:O(n)