题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

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

    int precedence(char op) {
        if (op == '+' || op == '-')
            return 1;
        if (op == '*')
            return 2;
        return 0;
    }

    int applyOperation(int a, int b, char op) {
        switch (op) {
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            default:
                return 0; // Handle other cases if needed
        }
    }

    int solve(const std::string& expression) {
        std::stack<int> numStack;
        std::stack<char> opStack;

        for (int i = 0; i < expression.length(); ++i) {
            if (std::isspace(expression[i]))
                continue;

            if (std::isdigit(expression[i])) {
                int num = 0;
                while (i < expression.length() && std::isdigit(expression[i])) {
                    num = num * 10 + (expression[i] - '0');
                    ++i;
                }
                --i;
                numStack.push(num);
            } else if (expression[i] == '(') {
                opStack.push('(');
            } else if (expression[i] == ')') {
                while (opStack.top() != '(') {
                    int b = numStack.top();
                    numStack.pop();
                    int a = numStack.top();
                    numStack.pop();
                    char op = opStack.top();
                    opStack.pop();
                    numStack.push(applyOperation(a, b, op));
                }
                opStack.pop(); // Pop '('
            } else {
                while (!opStack.empty() &&
                        precedence(opStack.top()) >= precedence(expression[i])) {
                    int b = numStack.top();
                    numStack.pop();
                    int a = numStack.top();
                    numStack.pop();
                    char op = opStack.top();
                    opStack.pop();
                    numStack.push(applyOperation(a, b, op));
                }
                opStack.push(expression[i]);
            }
        }

        while (!opStack.empty()) {
            int b = numStack.top();
            numStack.pop();
            int a = numStack.top();
            numStack.pop();
            char op = opStack.top();
            opStack.pop();
            numStack.push(applyOperation(a, b, op));
        }

        return numStack.top();
    }
};

全部评论

相关推荐

人力小鱼姐:实习经历没有什么含金量,咖啡店员迎宾这种就别写了,其他两段包装一下 想找人力相关的话,总结一下个人优势,结合校园经历里有相关性的部分,加一段自我评价
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务