[LeetCode]224. Basic Calculator
224. Basic Calculator
栈
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
total = 0
ops = [1, 1]
while i < len(s):
if not s[i].isspace():
if s[i].isdigit():
start = i
while i < len(s) and s[i].isdigit():
i += 1
total += ops.pop() * int(s[start:i])
continue
elif s[i] in '+-(':
ops.append(ops[-1] * (1, -1)[s[i]=='-'])
elif s[i] == ')':
ops.pop()
i += 1
return total
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
res, num, flag = 0, 0, 1
stack = []
for c in s:
if c.isdigit():
# 保存之前的num,计算当前的num
num = 10*num+ord(c)-ord('0')
elif c in '+-':
res += flag*num
num = 0
flag = (1, -1)[c == '-']
elif c == '(':
# 将现在的结果和括号的符号弹入保存下来,方便以后取出使用
stack.append(res)
stack.append(flag)
# 重置res和flag,以便计算括号中的结果
res = 0
flag = 1
elif c==')':
# 累加括号中的最后一位数
res += flag*num
# 取出之前保存括号外的符号
scope_res = stack.pop() * res
# 取出括号外的和,和括号内的和进行累加
res = stack.pop() + scope_res
num = 0
res += flag*num
return res
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法