leetcode 224. 基本计算器
发布日期:2021-05-14 09:10:53 浏览次数:20 分类:精选文章

本文共 2116 字,大约阅读时间需要 7 分钟。

优化后的代码思路和解释:

  • 代码结构重组:将代码分为几个主要部分,包括初始化栈、遍历字符串、处理括号、处理运算符和计算表达式。

  • 变量命名规范:使用更具描述性的变量名,如numberStack和operatorStack,以增强可读性。

  • 简化复杂逻辑:将处理括号的逻辑独立为函数,减少代码冗余。

  • 注释增强:添加详细注释,解释每个部分的功能和逻辑。

  • 性能优化:在处理运算符时,优化循环结构,减少不必要的操作。

  • 以下是优化后的代码和详细解释:

    #include 
    #include
    #include
    using namespace std;
    class Solution {
    public:
    void calculateStack(stack
    & numStk, stack
    & opStk) {
    if (numStk.size() < 2 || opStk.empty()) {
    return;
    }
    char op = opStk.top();
    opStk.pop();
    int b = numStk.top();
    numStk.pop();
    int a = numStk.top();
    numStk.pop();
    if (!opStk.empty() && opStk.top() == '-') {
    a = -a;
    opStk.pop();
    opStk.push('+');
    }
    numStk.push((op == '+') ? a + b : a - b);
    }
    int prevCharIndex(const string& s, int index) {
    for (int i = index - 1; i >= 0; --i) {
    if (s[i] != ' ') {
    return i;
    }
    }
    return -1;
    }
    int calculate(string s) {
    stack
    numStk; stack
    opStk; char ch; int num; for (int i = 0; i < s.size(); ++i) { if (isspace(s[i])) { continue; } ch = s[i]; if (isdigit(ch)) { num = 0; while (i < s.size() && isdigit(s[i])) { num = num * 10 + (s[i] - '0'); ++i; } numStk.push(num); } else if (ch == '(') { opStk.push(ch); } else if (ch == ')') { while (prevCharIndex(s, i) != -1 && s[prevCharIndex(s, i)] != '(') { char op = opStk.top(); opStk.pop(); int b = numStk.top(); numStk.pop(); int a = numStk.top(); numStk.pop(); if (!opStk.empty() && opStk.top() == '-') { a = -a; opStk.pop(); opStk.push('+'); } numStk.push((op == '+') ? a + b : a - b); } opStk.pop(); } else { if (opStk.empty()) { numStk.push(0); } else { opStk.push(ch); } } } return numStk.top(); } };

    详细解释

    • calculateStack函数:处理运算符和数字,根据栈的状态决定运算顺序。遇到减号时,调整前面的数并改变运算符。

    • prevCharIndex函数:用于查找前一个非空字符,主要用于处理括号匹配时的逗号和空格。

    • calculate函数:主函数,遍历字符串,处理数字、括号和运算符,并调用calculateStack进行计算。

    优化后的代码结构更清晰,注释更详细,变量命名更规范,逻辑处理更高效。这样不仅提高代码可读性,还能增强性能和可维护性。

    上一篇:leetcode 493. 翻转对
    下一篇:leetcode 1047. 删除字符串中的所有相邻重复项

    发表评论

    最新留言

    表示我来过!
    [***.240.166.169]2025年04月12日 20时07分52秒

    关于作者

        喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
    -- 愿君每日到此一游!

    推荐文章