给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。
示例 1:
输入:s = “1 + 1”
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = “(1+(4+5+2)-3)+(6+8)”
输出:23
提示:
1 <= s.length <= 3 * 105
s 由数字、‘+’、‘-’、‘(’、‘)’、和 ’ ’ 组成
s 表示一个有效的表达式
‘+’ 不能用作一元运算(例如, “+1” 和 “+(2 + 3)” 无效)
‘-’ 可以用作一元运算(即 “-1” 和 “-(2 + 3)” 是有效的)
输入中不存在两个连续的操作符
每个数字和运行的计算将适合于一个有符号的 32位 整数
我的解法
class Solution:
def calculate(self, s: str) -> int:
stack, num, sign = [], None, 1
for c in s:
# 空白就跳过
if c == ' ':
continue
# 数字就暂存
if c in "1234567890":
if num is None:
num = 0
num = num * 10 + int(c)
continue
# 非数字首先看看是否可以入栈数字
if num is not None:
stack.append(sign * num)
num, sign = None, 1
if c == "(":
if sign == -1:
stack.append("-")
sign = 1
stack.append(c)
elif c in ("+", "-"):
if not stack or stack[-1] in ("+", "-", "(", ")"):
sign = 2 * (c == "+") - 1
else:
stack.append(c)
else:# c == ")"
_num = 0
while True:
a = stack.pop()
if a == "(":
stack.append(_num)
break
else:
if stack[-1] in ("+", "-"):
_num += a * (2 * (stack.pop() == "+") - 1)
else:
_num += a
if num is not None:
stack.append(sign * num)
num, sign =0, 1
for c in stack:
if c in ("+", "-"):
sign = 2 * (c == "+") - 1
else:
num += sign * c
return num
from collections import deque
from operator import add, sub, mul, truediv, mod, pow
class Solution:
def calculate(self, s: str) -> int:
# 预处理字符串
# 1. 去除空格
# 2. 处理单目运算符 +-
_s = []
for idx, c in enumerate(s):
if c == ' ':
continue
if c in ("+", "-") and (not _s or _s[-1] == "("):
_s.append('0')
_s.append(c)
s = "".join(_s)
priority = {"+": 1, "-": 1, "*": 2, "/": 2, "%": 2, "^": 3}
operation = {"+": add, "-": sub, "*":mul, "/": lambda a, b: int(truediv(a, b)), "%": mod, "^": pow}
nums = deque([]) # 操作数栈
ops = deque([]) # 操作符栈
i, n = 0, len(s)
while i<n:
c = s[i]
# 解析操作数
if c.isdigit():
j, _num = i, 0
while j < n and s[j].isdigit():
_num = _num * 10 + int(s[j])
j += 1
nums.append(_num)
i = j - 1
elif c == "(":
ops.append(c)
elif c in operation.keys():
while ops and ops[-1] != "(" and priority[ops[-1]] >= priority[c]:
b, a, o = nums.pop(), nums.pop(), ops.pop()
nums.append(operation[o](a, b))
ops.append(c)
else: # c == ")"
while ops and ops[-1] != "(":
b, a, o = nums.pop(), nums.pop(), ops.pop()
nums.append(operation[o](a, b))
if ops and ops[-1] == "(":
ops.pop()
i += 1
while ops and ops[-1] != "(":
b, a, o = nums.pop(), nums.pop(), ops.pop()
nums.append(operation[o](a, b))
return nums.pop()
print(Solution().calculate("-1 + (-1+(4+5+2)-3)+(6+8)")) # '0-1+(0-1+(4+5+2)-3)+(6+8)'