逆波兰表达式求值

  1. class Solution:
  2.     def evalRPN(self, tokens: List[str]) -> int:
  3.         stack=[]
  4.         for i in range(len(tokens)):
  5.             if tokens[i].isdigit() or (len(tokens[i])>1 and tokens[i][1].isdigit()):
  6.                 stack.append(tokens[i])
  7.             else:
  8.                 temp1=stack.pop()
  9.                 temp2=stack.pop()
  10.                 stack.append(str(int(eval(temp2+tokens[i]+temp1))))         (int为了取整)
  11.         return int(stack.pop())

不能把整个式子用eval求值,因为有很多隐形的括号,有很多优先计算的式子:

  1. class Solution:
  2.     def evalRPN(self, tokens: List[str]) -> int:
  3.         stack=[]
  4.         for i in range(len(tokens)):
  5.             if tokens[i].isdigit() or (len(tokens[i])>1 and tokens[i][1].isdigit()):
  6.                 stack.append(tokens[i])
  7.             else:
  8.                 temp=stack.pop()
  9.                 stack.append(tokens[i])
  10.                 stack.append(temp)
  11.         return ''.join(stack)(错误的)

发表评论