python-leetcode-基本计算器
class Solution:
def calculate(self, s: str) -> int:
stack = []
num = 0
sign = 1 # 1 表示正号,-1 表示负号
result = 0
for char in s:
if char.isdigit():
num = num * 10 + int(char)
elif char == '+':
result += sign * num
sign = 1
num = 0
elif char == '-':
result += sign * num
sign = -1
num = 0
elif char == '(':
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif char == ')':
result += sign * num
result *= stack.pop() # 弹出符号
result += stack.pop() # 弹出之前的结果
num = 0
result += sign * num
return result
原文地址:https://blog.csdn.net/Lucy_wzw/article/details/145150777
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!