左程云大神的Java代码,抄过来改成Python版本的。一开始用的list,超时了,改成deque,顺利通过。
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @return int整型 # from collections import deque class Solution: def calculate(self , s: str) -> int: # write code here dd = deque() cur = 0 i = 0 while i <len(s): if s[i] >='0' and s[i] <='9': cur = cur *10 +int(s[i]) i += 1 else: self.addNum(dd,cur,s[i]) i += 1 cur = 0 self.addNum(dd,cur,'&') return self.getAns(dd) def addNum(self,dd,num,op): if len(dd) == 0: dd.append(num) dd.append(op) elif dd[-1] == '*' or dd[-1] == '/': top = dd.pop() pre = dd.pop() num = pre*num if top == '*' else pre/num dd.append(num) dd.append(op) else: dd.append(num) dd.append(op) def getAns(self,dd): ans = int(dd.popleft()) while len(dd) > 1: op = dd.popleft() num = int(dd.popleft()) ans =ans+ num if op == '+' else ans-num return ans