LeetCode 224. 基本计算器

LeetCode 224. 基本计算器

给你一个字符串表达式 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)'
  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值