链接: 基本计算器 II
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(" ", "").replace("(-", "(0-")
priority = {"+":1, "-":1, "*":2, "/":2}
ops = []
nums = []
i = 0
while i < len(s):
if self.is_digit(s[i]):
n = 0
while i < len(s) and self.is_digit(s[i]):
n = n*10 + ord(s[i]) - ord('0')
i += 1
nums.append(n)
else:
if s[i] == "(":
ops.append("(")
i += 1
elif s[i] == ")":
while ops[-1] != "(":
op = ops.pop()
n1 = nums.pop()
n2 = nums.pop()
n = self.carryout(op, n1, n2)
nums.append(n)
ops.pop()
i += 1
else:
while ops and priority[ops[-1]] >= priority[s[i]]:
op = ops.pop()
n1 = nums.pop()
n2 = nums.pop()
n = self.carryout(op, n1, n2)
nums.append(n)
ops.append(s[i])
i += 1
while ops:
op = ops.pop()
n1 = nums.pop()
n2 = nums.pop()
n = self.carryout(op, n1, n2)
nums.append(n)
return nums[-1]
def is_digit(self, ch):
return ord('0') <= ord(ch) <= ord('9')
def carryout(self, op, n1, n2):
if op == "+":
return n1 + n2
elif op == "-":
return n2 - n1
elif op == "*":
return n1 * n2
elif op == "/":
return n2 // n1