力扣刷题:27-基本计算器 II(227)

151 阅读1分钟

这道题借用两个栈来实现,一个操作数栈,一个操作符栈,如果遇到操作数,直接入栈,如果遇到操作符,由于优先级的关系,如果此操作符没有栈顶的操作符优先级高,则先将栈顶的运算符出栈进行运算。同时,为了将栈中的所有运算符“逼出”,在整个运算表达式的末尾,还增加了一个虚拟运算符,它的优先级比所有运算符都低,只要它一出场,操作符栈中的操作符全部要出栈进行运算。最后,操作数栈留下的最后一个数,就是表达式的结果。

下面是使用C++语言实现的代码。

class Solution {
public:
    int level(char op) {
        switch (op) {
            case '+':
            case '-':
                return 1;
            case '*':
            case '/':
                return 2;
            case '@':
                return -1;
        }
        return 0;
    }
    int cal(int num1, char op, int num2) {
        switch (op) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                return num1 / num2;
        }
        return 0;
    }
    int calculate(string s) {
        stack<int> operand;
        stack<char> operate;
        s += '@';
        for (int i = 0, num = 0; i < s.size(); i++) {
            if (s[i] == ' ') {
                continue;
            }
            if (level(s[i]) == 0) {
                num = num * 10 + (s[i] - '0');
                continue;
            }
            operand.push(num);
            num = 0;
            while (!operate.empty() && level(operate.top()) >= level(s[i])) {
                int num2 = operand.top();
                operand.pop();
                int num1 = operand.top();
                operand.pop();
                operand.push(cal(num1, operate.top(), num2));
                operate.pop();
            }
            operate.push(s[i]);
        }
        return operand.top();
    }
};