class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
total = 0
i, signs = 0, [1, 1]
while i < len(s):
c = s[i]
if c.isdigit():
start = i
while i < len(s) and s[i].isdigit():
i += 1
total += signs.pop() * int(s[start:i])
continue
if c in '+-(':
signs += signs[-1] * (1, -1)[c == '-'],
elif c == ')':
signs.pop()
i += 1
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
total = 0
i, signs = 0, [1, 1]
while i < len(s):
c = s[i]
if c.isdigit():
start = i
while i < len(s) and s[i].isdigit():
i += 1
total += signs.pop() * int(s[start:i])
continue
if c in '+-(':
signs += signs[-1] * (1, -1)[c == '-'],
elif c == ')':
signs.pop()
i += 1
return total
https://leetcode.com/problems/basic-calculator/#/description
本文介绍了一个基本计算器算法的实现,该算法能够处理包含加减运算及括号表达式的字符串,并正确计算其结果。通过使用栈来跟踪当前的符号状态,算法可以有效地解析复杂的数学表达式。
4万+

被折叠的 条评论
为什么被折叠?



