用了一个栈,当遇到(时, 把当前的结果存起来,以及括号前面的符号存起来,result置为零,重新开始算,遇到)把result * 前面存下来的符号 加上(前面的result
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
sign = 1
result = 0
i = 0
stack = []
while i < len(s):
if s[i] == ' ':
i += 1
elif s[i] >= '0' and s[i] <= '9':
sum = int(s[i])
while i + 1 < len(s) and s[i+1] >= '0' and s[i+1] <= '9':
i += 1
sum = sum * 10 + int(s[i])
result += sum * sign
i += 1
elif s[i] == '+':
sign = 1
i += 1
elif s[i] == '-':
sign = -1
i += 1
elif s[i] == '(':
stack.append(result)
stack.append(sign)
result = 0
sign = 1
i += 1
elif s[i] == ')':
result = result * stack.pop()
result += stack.pop()
i += 1
return result
网友评论