- class Solution:
- def evalRPN(self, tokens: List[str]) -> int:
- stack=[]
- for i in range(len(tokens)):
- if tokens[i].isdigit() or (len(tokens[i])>1 and tokens[i][1].isdigit()):
- stack.append(tokens[i])
- else:
- temp1=stack.pop()
- temp2=stack.pop()
- stack.append(str(int(eval(temp2+tokens[i]+temp1)))) (int为了取整)
- return int(stack.pop())
不能把整个式子用eval求值,因为有很多隐形的括号,有很多优先计算的式子:
- class Solution:
- def evalRPN(self, tokens: List[str]) -> int:
- stack=[]
- for i in range(len(tokens)):
- if tokens[i].isdigit() or (len(tokens[i])>1 and tokens[i][1].isdigit()):
- stack.append(tokens[i])
- else:
- temp=stack.pop()
- stack.append(tokens[i])
- stack.append(temp)
- return ''.join(stack)(错误的)