class Solution:
"""
@param s: the expression string
@return: the answer
"""
def calculate(self, s):
# Write your code here
order = {'+': 0, '-':0, '*': 1, '/':1}
stack = []
num = 0
for c in s:
if c.isdigit():
num = num * 10 + int(c)
if c in '+-*/':
while stack and stack[-1] != '(' and order[stack[-1]] >= order[c]:
op = stack.pop()
pre = stack.pop()
num = self.calc(pre, num, op)
stack.append(num)
stack.append(c)
num = 0
if c is '(':
stack.append(c)
if c is ')':
while stack[-1] != '(':
op = stack.pop()
pre = stack.pop()
num = self.calc(pre, num, op)
stack.pop()
while stack:
op = stack.pop()
pre = stack.pop()
num = self.calc(pre, num, op)
return num
def calc(self, a, b, op):
if op == '+':
return a + b
if op == '-':
return a - b
if op == '*':
return a * b
if op == '/':
return a // b
class Solution:
"""
@param s: the expression string
@return: the answer
"""
def __init__(self) :
self.i = 0
def parseExpr(self ,s) :
nums = []
op = '+'
while self.i < len(s) and op != ')' : #遇到右括号退出递归
if s[self.i] == ' ' :
self.i += 1
continue
if s[self.i] == '(' : #遇到左括号进入递归
self.i += 1
n = self.parseExpr(s)
else :
n = self.parseNum(s) #字符串转化数字
if op == '+' : #加法
nums.append(n)
elif op == '-' : #减法
nums.append(-n)
elif op == '*' : #乘法
nums[-1] *= n
elif op == '/' : #除法
nums[-1] //= n
if self.i >= len(s) :
break
op = s[self.i]
self.i += 1
res = 0
for n in nums :
res += n
return res
def parseNum(self, s) :
n = 0
while self.i < len(s) and s[self.i] >= '0' and s[self.i] <='9' :
n = ord(s[self.i]) - ord('0') + 10 * n
self.i += 1
return n
def calculate(self, s):
# Write your code here
return self.parseExpr(s)