LeetCode 227. 基本计算器 II

227. 基本计算器 II

给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。

整数除法仅保留整数部分。

你可以假设给定的表达式总是有效的。所有中间结果将在 [-2^31, 2^31 - 1] 的范围内。

注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。

示例 1:

输入:s = "3+2*2"
输出:7

示例 2:

输入:s = " 3/2 "
输出:1

示例 3:

输入:s = " 3+5 / 2 "
输出:5

提示:

  • 1 <= s.length <= 3 * 10^5
  • s 由整数和算符 ('+', '-', '*', '/') 组成,中间由一些空格隔开
  • s 表示一个 有效表达式
  • 表达式中的所有整数都是非负整数,且在范围 [0, 2^31 - 1] 内
  • 题目数据保证答案是一个 32-bit 整数

解法1:栈

同类题型详解:  LeetCode 224. 基本计算器-CSDN博客 LeetCode 772. 基本计算器 III-CSDN博客

算法逻辑

  1. 双栈结构:使用两个栈,opStack(操作符栈)和numStack(数字栈)。
  2. 遍历字符串:逐个字符读取字符串,根据当前字符是数字还是操作符,执行不同的逻辑。
  3. 处理数字:构建完整的数字并压入数字栈。
  4. 处理操作符:根据当前操作符和栈顶操作符的优先级,执行相应的运算,并将结果压回数字栈,然后将当前操作符压入操作符栈。
  5. 优先级规则:乘法和除法优先于加法和减法,相同优先级的运算按照从左到右的顺序执行。

算法实现步骤

  1. 初始化:创建两个栈 opStacknumStack

  2. 字符串预处理:去除字符串中的所有空格。

  3. 遍历字符串:使用一个指针 i 从左到右遍历字符串 s

  4. 数字处理

    • 如果当前字符 c 是数字,连续读取形成整数 num,将其压入 numStack
  5. 操作符处理

    • 如果当前字符 c 是操作符,执行以下操作:
      • 使用辅助函数 stackHiger 判断当前操作符与栈顶操作符的优先级关系。
      • 如果当前操作符优先级低于或等于栈顶操作符,从 opStack 弹出操作符,从 numStack 弹出两个数字,执行运算,并将结果压回 numStack。重复此过程直到 opStack 为空或当前操作符优先级更高。
      • 将当前操作符压入 opStack
  6. 最终计算

    • 字符串遍历完成后,如果 opStack 中仍有操作符,继续执行运算直到 opStack 为空。
  7. 返回结果numStack 的栈顶元素即为最终的计算结果。

Java版:

class Solution {
    public int calculate(String s) {
        Deque<Character> opStack = new ArrayDeque<>();
        Deque<Integer> numStack = new ArrayDeque<>();
        s = s.replaceAll(" ", "");
        int i = 0;
        int n = s.length();
        while (i < n) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                int num = 0;
                while (i < n && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + (s.charAt(i) - '0');
                    i++;
                }
                i--;
                numStack.push(num);
            } else {
                while (!opStack.isEmpty() && stackHiger(c, opStack.peek())) {
                    char op = opStack.pop();
                    int num2 = numStack.pop();
                    int num1 = numStack.pop();
                    switch (op) {
                        case '+':
                            numStack.push(num1 + num2);
                            break;
                        case '-':
                            numStack.push(num1 - num2);
                            break;
                        case '*':
                            numStack.push(num1 * num2);
                            break;
                        case '/':
                            numStack.push(num1 / num2);
                            break;
                    }
                }
                opStack.push(c);
            }
            i++;
        }

        while (!opStack.isEmpty() ) {
            char op = opStack.pop();
            int num2 = numStack.pop();
            int num1 = numStack.pop();
            switch (op) {
                case '+':
                    numStack.push(num1 + num2);
                    break;
                case '-':
                    numStack.push(num1 - num2);
                    break;
                case '*':
                    numStack.push(num1 * num2);
                    break;
                case '/':
                    numStack.push(num1 / num2);
                    break;
            }
        }

        return numStack.peek();
    }

    private boolean stackHiger(char c, char peek) {
        if ((c == '*' || c == '/') && (peek == '+' || peek == '-')) {
            return false;
        }
        return true;
    }
}

Python3版:

class Solution:
    def calculate(self, s: str) -> int:
        def stackHiger(c, peek) -> bool:
            if c in '*/' and peek in '+-':
                return False
            return True


        opStack = []
        numStack = []
        s = s.replace(" ", "")
        n = len(s)
        i = 0
        while i < n:
            if s[i].isdigit():
                num = 0
                while i < n and s[i].isdigit():
                    num = num * 10 + int(s[i])
                    i += 1
                i -= 1
                numStack.append(num)
            else:
                while opStack and stackHiger(s[i], opStack[-1]):
                    op = opStack.pop()
                    num2 = numStack.pop()
                    num1 = numStack.pop()
                    match op:
                        case '+':
                            numStack.append(num1 + num2)
                        case '-':
                            numStack.append(num1 - num2)
                        case '*':
                            numStack.append(num1 * num2)
                        case '/':
                            numStack.append(num1 // num2)
                
                opStack.append(s[i])
            i += 1
        
        while opStack:
            op = opStack.pop()
            num2 = numStack.pop()
            num1 = numStack.pop()
            match op:
                case '+':
                    numStack.append(num1 + num2)
                case '-':
                    numStack.append(num1 - num2)
                case '*':
                    numStack.append(num1 * num2)
                case '/':
                    numStack.append(num1 // num2)

        return numStack[-1]

复杂度分析

  • 时间复杂度:O(n),其中 n 是字符串 s 的长度。每个字符都被遍历一次,每个操作符和数字的入栈和出栈操作都是常数时间的。
  • 空间复杂度:O(n),最坏情况下,所有字符都可能是数字或操作符,需要存储在栈中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值