题解 |栈| #中缀表达式求值!!!!#

描述

请写一个整数计算器,支持加减乘三种运算和括号。

数据范围:0≤∣s∣≤1000≤∣s∣≤100,保证计算结果始终在整型范围内

要求:空间复杂度: O(n)O(n),时间复杂度 O(n)O(n)

示例1

输入:"1+2"

返回值:3

示例2

输入:"(2*(3-4))*5"

返回值:-10

示例3

输入:"3+2*3*4-1"

返回值:26

一、使用逆波兰表达式转化法

        在前面的栈的使用中,我使用了栈进行逆波兰表达式求值操作,并在其中补充了将中缀表达式转化为逆波兰表达式(后缀表达式)的操作。现在进行回忆。

(一)中缀表达式转化为逆波兰表达式

// 将字符串拆分为 token
vector<string> tokenize(const string& s) {
    vector<string> tokens;
    string currentToken;
    for (char c : s) {
        if (isdigit(c) || c == '.') {
            // 如果是数字或小数点,则添加到当前 token
            currentToken += c;
        } else if (c == ' ') {
            // 如果是空格,则跳过
            continue;
        } else {
            // 如果是操作符或其他字符,则将当前 token 添加到 tokens 并清空
            if (!currentToken.empty()) {
                tokens.push_back(currentToken);
                currentToken.clear();
            }
            // 将操作符或其他字符作为一个 token
            tokens.push_back(string(1, c));
        }
    }
    // 处理最后一个 token
    if (!currentToken.empty()) {
        tokens.push_back(currentToken);
    }
    return tokens;
}

// 将中缀表达式转换为后缀表达式
    vector<string> infixToPostfix(const string& s) {
        stack<string> operators;
        vector<string> output;
        unordered_map<string, int> precedence = {{"+", 1}, {"-", 1}, {"*", 2}, {"/", 2}};

        vector<string> tokens = tokenize(s);

        for (const auto& token : tokens) {
            if (isdigit(token[0])) {
                output.push_back(token);
            } else if (token == "(") {
                operators.push(token);
            } else if (token == ")") {
                while (!operators.empty() && operators.top() != "(") {
                    output.push_back(operators.top());
                    operators.pop();
                }
                operators.pop(); // Pop the '('
            } else if (precedence.count(token)) {  // Check if it's an operator
                while (!operators.empty() && precedence[token] <= precedence[operators.top()]) {
                    output.push_back(operators.top());
                    operators.pop();
                }
                operators.push(token);
            }
        }

        while (!operators.empty()) {
            output.push_back(operators.top());
            operators.pop();
        }

        return output;
    }

(二)逆波兰表达式求值

//逆波兰运算
    int evalRPN(vector<string>& tokens) {
        using namespace std;
        // write code here
        int l = 0;
        int r = 0;
        stack<int> stac;
        for (string str : tokens) {
            if ((str != "+" ) && (str != "-") && (str != "*") && (str != "/")) {
                stac.push(stoi(str) );
            } else {
                int r = stac.top();
                stac.pop();
                int l = stac.top();
                stac.pop();
                if (str == "+") {
                    stac.push(l + r);
                } else if (str == "-") {
                    stac.push(l - r);
                } else if (str == "*") {
                    stac.push(l * r);
                } else if (str == "/") {
                    stac.push(l / r);
                }
            }
        }
        return stac.top();

    }

(三)调用函数


//中缀表达式转化为逆波兰表达式后进行运算
    int solve(string s) {
        // write code here
        vector<string> tokens = infixToPostfix(s);
        return evalRPN(tokens);

    }

二、直接在栈上进行运算

        在实践中我发现,先进行转化在进行计算有些浪费,我认为可以将转化这一步改成计算。

#include <map>
#include <stack>
#include <string>
#include <iostream>
using namespace std;
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 返回表达式的值
     * @param s string字符串 待计算的表达式
     * @return int整型
     */

    // 判断优先级
    int precedence(char op) {
        if (op == '+' || op == '-') return 1;
        if (op == '*' || op == '/') return 2;
        return 0;
    }

// 计算两个数字的值
    int applyOp(int a, int b, char op) {
        switch (op) {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                return a / b;
        }
        return 0;
    }

    int solve(const string& s) {
        // write code here
        stack<int> values;  // 用于存储数字
        stack<char> ops;    // 用于存储运算符和括号

        for (size_t i = 0; i < s.size(); ++i) {
            char ch = s[i];
            if (isdigit(ch)) {
                // 构造完整的数字
                int num = 0;
                while (i < s.size() && isdigit(s[i])) {
                    num = num * 10 + (s[i] - '0');
                    ++i;
                }
                --i;  // 因为循环会自动增加 i,所以这里需要减一
                values.push(num);  // 将数字压入栈
            } else if (ch == '(') {
                // 左括号直接压入栈
                ops.push(ch);
            } else if (ch == ')') {
                // 遇到右括号时,弹出栈中的元素进行计算,直到遇到左括号
                while (!ops.empty() && ops.top() != '(') {
                    int val2 = values.top();
                    values.pop();
                    int val1 = values.top();
                    values.pop();
                    char op = ops.top();
                    ops.pop();
                    values.push(applyOp(val1, val2, op));
                }
                if (!ops.empty()) ops.pop();  // 弹出左括号
            } else {
                // 遇到运算符时,与栈顶运算符比较优先级
                while (!ops.empty() && precedence(ops.top()) >= precedence(ch)) {
                    int val2 = values.top();
                    values.pop();
                    int val1 = values.top();
                    values.pop();
                    char op = ops.top();
                    ops.pop();
                    values.push(applyOp(val1, val2, op));
                }
                ops.push(ch);  // 将当前运算符压入栈
            }
        }

        // 处理剩余的运算符
        while (!ops.empty()) {
            int val2 = values.top();
            values.pop();
            int val1 = values.top();
            values.pop();
            char op = ops.top();
            ops.pop();
            values.push(applyOp(val1, val2, op));
        }

        // 最终结果在栈顶
        return values.top();
    }
};

算法思路: 1. 创建两个:一个操作数和一个操作符。 2. 从左到右遍历表达式,遇到操作数就压入操作数,遇到操作符就与操作符中的顶元素比较优先级。 3. 如果当前操作符的优先级大于操作符顶的操作符优先级,就将当前操作符压入操作符。 4. 如果当前操作符的优先级小于或等于操作符顶的操作符优先级,就从操作数中弹出两个操作数,从操作符中弹出一个操作符,进行计算并将结果压入操作数,重复步骤3,直到当前操作符的优先级大于操作符顶的操作符优先级。 5. 当遍历完表达式后,如果操作符中还有操作符,就将操作数中剩余的操作数和操作符中的操作符按照步骤4计算,直到操作符为空。 6. 操作数中最后剩下的元素就是表达式的值。 算法实现: ```python def calculate(s: str) -> int: # 定义操作符优先级 priority = {'+': 1, '-': 1, '*': 2, '/': 2} # 定义操作数和操作符 nums = [] ops = [] i = 0 while i < len(s): # 跳过空格 if s[i] == ' ': i += 1 continue # 如果是数字,压入操作数 if s[i].isdigit(): j = i while j < len(s) and s[j].isdigit(): j += 1 nums.append(int(s[i:j])) i = j # 如果是操作符,比较优先级 else: while ops and priority[ops[-1]] >= priority[s[i]]: b = nums.pop() a = nums.pop() op = ops.pop() if op == '+': nums.append(a + b) elif op == '-': nums.append(a - b) elif op == '*': nums.append(a * b) elif op == '/': nums.append(int(a / b)) ops.append(s[i]) i += 1 # 处理剩余的操作符 while ops: b = nums.pop() a = nums.pop() op = ops.pop() if op == '+': nums.append(a + b) elif op == '-': nums.append(a - b) elif op == '*': nums.append(a * b) elif op == '/': nums.append(int(a / b)) # 返回操作数中最后剩下的元素 return nums[-1] ``` 算法分析: 1. 时间复杂度:遍历一遍表达式,时间复杂度为O(n);操作符和操作数中每个元素都只进出一次,所以总时间复杂度为O(n)。 2. 空间复杂度:操作符和操作数的最大长度为表达式的长度,所以空间复杂度为O(n)。 参考链接: 1. [LeetCode官方题解](https://leetcode-cn.com/problems/basic-calculator-ii/solution/jian-dan-zhan-jie-fa-by-jerry_nju/) 2. [算法珠玑(第2版)](https://book.douban.com/subject/33437322/)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值