LintCode 978: Basic Calculator 栈好题

本文围绕基本计算器表达式求值展开,表达式含括号、加减号、非负整数和空格。介绍了四种解法,包括先转换为逆波兰表达式处理、借助变量和栈计算、在括号间用递归以及参考labuladong的解法,还提及二刷时可用vector代替stack。

978 · Basic Calculator
Algorithms
Medium

Description
Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ‘(’ and closing parentheses ‘)’, the plus ‘+’ or minus sign ‘-’, non-negative integers and empty spaces ’ '.

You may assume that the given expression is always valid.

Do not use the eval built-in library function.

Example
Example 1

Input:“1 + 1”
Output:2
Example 2

Input:“(1+(4+5+2)-3)+(6+8)”
Output:23
Tags
Company
Airbnb
Facebook
Google
Related Problems

424
Evaluate Reverse Polish Notation
Medium

849
Basic Calculator III
Hard

980
Basic Calculator II
Medium

解法1:先tokenize,然后转换成逆波兰表达式RPN,再处理RPN,跟LintCode 424一样的方法。
注意:
1.我们常用的容易阅读的表达式1+2*3是中序遍历
2. 逆波兰表达式是1 2 3 *+是后序遍历
3. 波兰表达式是+1 * 2 3是前序遍历

波兰和逆波兰有个好处就是不需要括号。

class Solution {
public:
    /**
     * @param s: the given expression
     * @return: the result of expression
     */
    int calculate(string &s) {
        int len = s.size();
        vector<string> tokens;
        
        //tokenize
        int pos = 0, orig_pos = 0;
        while (pos < len) {
            while (pos < len && s[pos] == ' ') pos++;
            if (pos == len) break;
            orig_pos = pos;
            if (!isdigit(s[pos])) {
                tokens.push_back(s.substr(pos, 1));
                pos++;
            }
            else {
                while(pos < len && isdigit(s[pos])) pos++;
                tokens.push_back(s.substr(orig_pos, pos - orig_pos));
            }
            
        }

        //generate RPN
        len = tokens.size();
        stack<string> optrStk;
        vector<string> RPN;
        map<string, int> prio;
        prio["+"] = 1;
        prio["-"] = 1;
        prio["*"] = 2;
        prio["/"] = 2;

        for (int i = 0; i < len; i++) {
            string token = tokens[i];
            if (token.size() > 1 || (token[0] >= '0' && token[0] <= '9')) {
                RPN.push_back(token);
                continue;
            }
            if (token == "(") {
                optrStk.push(token);
                continue;
            }
            if (token == ")") {
                while (!optrStk.empty() && optrStk.top() != "(") {
                    RPN.push_back(optrStk.top());
                    optrStk.pop();
                }
                optrStk.pop();  //pop "("
                continue;
            }
            while (!optrStk.empty() && prio[optrStk.top()] >= prio[token]) {
                RPN.push_back(optrStk.top());
                optrStk.pop();
            }
            optrStk.push(token);
        }
        //dump the rest in optrStr to RPN
        while (!optrStk.empty()) {
            RPN.push_back(optrStk.top());
            optrStk.pop();
        }

        //process RPN
        stack<int> RPNStk;
        len = RPN.size();
        if (len == 0) return 0;
        if (len == 1) return stoi(RPN[0]);
        for (int i = 0; i < len; i++) {
            string token = RPN[i];
            if (token.size() > 1 || (token[0] >= '0' && token[0] <= '9')) {
                RPNStk.push(stoi(token));
                continue;
            } else {
                int top1 = RPNStk.top(); RPNStk.pop();
                int top2 = RPNStk.top(); RPNStk.pop();
                int result = 0;
                switch (RPN[i][0]) {
                    case '*': result = top2 * top1; break;
                    case '/': result = top2 / top1; break;
                    case '+': result = top2 + top1; break;
                    case '-': result = top2 - top1; break;
                    default: break;
                }
                RPNStk.push(result);
            }
        }
        return RPNStk.top();
    }
};

解法2:参考的九章的解法,我觉得很不错。原文如下:
"
我们需要三个变量和一个栈: number表示当前的操作数, sign表示当前的操作数应该被加还是被减, result表示结果.
初始number, result = 0, sign = 1, 开始遍历字符串:
碰到数字则追加到number尾端
碰到加号说明上一个数字已经完全被计算至number, 这时应该把number * sign加到result中, 然后把sign置为1 (因为当前碰到了加号)
碰到减号, 同上, 不同的在于最后要把sign置为-1
碰到左括号, 说明这时要优先出右边的表达式, 需要将result和sign压入栈中(注意, 此时的sign表示的是这个括号内的表达式应该被result加上还是减去), 然后初始化result和sign, 准备计算括号内的表达式
碰到右括号, 说明一个括号内的表达式被计算完了, 此时需要从栈中取出该括号之前的sign和result, 与当前的result相加运算 (注意, 是原来的result + sign * 当前result)
注意, 一个合法的表达式, 左括号之前一定不会是数字, 右括号之前一定是一个数字. 所以碰到右括号不要忘了先把number * sign加到当前result里.
以及, 循环结束后number可能还有数字, 需要加到result里. (比如"1+2"这样的表达式, 2并不会在循环内被加到结果中)
"

class Solution {
public:
    /**
     * @param s: the given expression
     * @return: the result of expression
     */
    int calculate(string &s) {
        int len = s.size();
        stack<int> stk;
        int res = 0, num = 0;
        int sign = 1;
        for (char c : s) {
            if (isdigit(c)) {
                num = num * 10 + c - '0';
                continue;
            }
            if (c == '+' || c == '-') {
                res += num * sign;
                num = 0;
                sign = (c == '+') ? 1 : -1;
                continue;
            }
            if (c == '(') {
                stk.push(res);
                stk.push(sign);
                sign = 1;
                res = 0;
                continue;
            }
            if (c == ')') {
                res += sign * num;
                int saved_sign = stk.top(); stk.pop();
                int saved_res = stk.top(); stk.pop();
                res = saved_res + saved_sign * res;
                num = 0;
                //sign = 1;
            }
        }
        if (num != 0) {
            res += sign * num;
        }
        return res;
    }
};

解法3:在解法2的基础上,我们可以在括号之间用递归,这里我们必须要确定左括号的个数和右括号的个数相等时,其内部才是一个完整的表达式,因此可以用递归,这里就是用系统栈来代替栈。

class Solution {
public:
    /**
     * @param s: the given expression
     * @return: the result of expression
     */
    int calculate(string &s) {
        int len = s.size();
        stack<int> stk;
        int res = 0, num = 0;
        int sign = 1;
        int bracket_cnt = 0;
        int i = 0;
        while (i < len) {
            char c = s[i];
            if (isdigit(c)) {
                num = num * 10 + c - '0';
            }
            else if (c == '+' || c == '-') {
                res += num * sign;
                num = 0;
                sign = (c == '+') ? 1 : -1;
            }
            else if (c == '(') {
                int orig_pos = i + 1;
                bracket_cnt = 1;
                while (i < len && bracket_cnt > 0) {
                    i++;
                    if (s[i] == '(') bracket_cnt++;
                    else if (s[i] == ')') bracket_cnt--;
                }
                
                string s2 = s.substr(orig_pos, i - orig_pos);
                int temp_res = calculate(s2);
                res += sign * temp_res;
                num = 0;
            }
            i++;
        }
        if (num != 0) {
            res += sign * num;
        }
        return res;
    }
};

解法4:参考的labuladong的解法。跟解法3差不多。
注意:
helper()里面的index必须用&,因为递归回来后,index的值就已经递增了。
递归完后,c=s[index]是更新后的index对应的字符。
如果不是最后一个字符,遇到运算符(非数字又非空格),要进switch()处理。如果是最后一个字符,不管是什么(空格也好,数字也好),也要进switch()处理,不然这最后一个数字就丢掉了。

class Solution {
public:
    int calculate(string s) {
        int index = 0;
        return helper(s, index);
    }
private:
    int helper(string &s, int &index) {
        stack<int> stk;
        int sLen = s.size();
        char sign = '+';
        int num = 0;
        int res = 0;
        for (; index < sLen; index++) {
            char c = s[index];
            if (c == '(') {
                index++;
                num = helper(s, index);
            }
            c = s[index];
            if (isdigit(c)) {
                num = num * 10 + (c - '0');
            } 
            if ((!isdigit(c) && c != ' ') || index == sLen - 1) { //(c == '+' || c == '-' || c == '*' || c == '/') or reach the end
                switch (sign) {
                    case '+':
                        stk.push(num);
                        break;
                    case '-':
                        stk.push(-num);
                        break;
                    case '*':
                        stk.push(stk.top() * num);
                        stk.pop();
                        break;
                    case '/':
                        stk.push(stk.top() / num);
                        stk.pop();
                        break;
                    default:
                    break;
                }
                sign = c;
                num = 0;
            }
            if (c == ')') {
                index++;
                break;
            }
        }
        
        while (!stk.empty()) {
            res += stk.top();
            stk.pop();
        }
        return res;
    }
};

二刷:跟上面差不多,用vector而不是stack。

class Solution {
public:
    /**
     * @param s: the given expression
     * @return: the result of expression
     */
    int calculate(string &s) {
        int index = 0;
        return calExpr(s, index);
    }
private:
    int calExpr(string &s, int &index) {
        int num = 0;
        char sign = '+';
        vector<int> res;
        while (index < s.size()) {
            if (s[index] == '(') {
                index++;
                num = calExpr(s, index);
                //res.push_back(sign * num); //不能push_back,要等到+-*/或index==s.size()-1再push_back
            }
            if (isdigit(s[index])) {
                num = num * 10 + (s[index] - '0');
                //不能continue,也不能index++, 因为可能最后一个字符就是数字
                //也不能push_back(),要等到+-*/或index==s.size()-1再push_back
            } 
            if ((!isdigit(s[index]) && s[index] != ' ')|| index == s.size() - 1) {
                if (sign == '+') {
                    res.push_back(num);
                } else if (sign == '-') {
                    res.push_back(-num);
                }
                sign = s[index];
                num = 0;
               // index++;
            }
            
            if (s[index] == ')') {
                index++; //这里要加index++,因为马上要break
                break;
            }
            index++;
        }
        int sum = 0;
        for (auto n : res) {
            sum += n;
        }
        return sum;
    }
};
<think>我们正在分析用户的问:在C++代码 `MyLib::Calculator calc;` 中,`calc` 是什么? 根据上下文,我们已知: - `MyLib` 是一个命名空间(namespace) - `Calculator` 是定义在 `MyLib` 命名空间中的一个类(class) 因此,`MyLib::Calculator calc;` 这行代码的含义是: 1. `MyLib::Calculator`:使用作用域解析运算符 `::` 访问命名空间 `MyLib` 中的 `Calculator` 类。 2. `calc`:是类 `MyLib::Calculator` 的一个实例(instance),即一个对象(object)。 具体解释: - 在C++中,类(class)是一种用户自定义的数据类型,它封装了数据(成员变量)和操作(成员函数)。 - 创建类的对象需要声明该类的变量,如这里的 `calc`。 - 当执行 `MyLib::Calculator calc;` 时,编译器会在(stack)上为 `calc` 对象分配内存,并调用 `Calculator` 类的默认构造函数(如果没有显式定义构造函数,编译器会生成一个默认的无参构造函数)。 注意:如果用户没有为类提供任何构造函数,编译器会自动生成一个默认构造函数。但如果用户提供了带参数的构造函数,那么除非显式地定义了一个无参构造函数,否则不能这样直接实例化(因为编译器不会再生成默认的无参构造函数)。 因此,`calc` 是 `MyLib::Calculator` 类的一个具体对象,我们可以通过它来调用类中的成员函数,例如: ```cpp int result = calc.add(2, 3); // 调用 calc 对象的 add 方法 ``` 总结: - `calc` 是一个对象,它是 `MyLib::Calculator` 类的一个实例。 现在,我们按照要求生成回答,并注意以下几点: - 使用中文回答 - 在适当位置添加引用标识(虽然用户提供的引用中没有直接相关的内容,但我们可以引用[^1]来提及C++与C的区别,因为命名空间是C++特有的) - 生成相关问 回答结构: 1. 解释 `MyLib::Calculator calc;` 的含义 2. 详细说明 `calc` 是什么 3. 补充说明对象创建的过程(构造函数) 4. 给出一个简单的示例代码片段 5. 生成相关问 注意:用户提供的引用[^1]提到C++的关键字(如class、namespace)在C中不被识别,我们可以利用这一点强调命名空间是C++的特性。</think>### 在C++中理解 `MyLib::Calculator calc;` 语句 在C++代码 `MyLib::Calculator calc;` 中,`calc` 是 `MyLib` 命名空间中 `Calculator` 类的一个**实例**(对象)。让我们逐步解析: #### 1. **命名空间解析** - `MyLib::` 表示访问 `MyLib` 命名空间中的成员 - 这是C++特有的特性,用于避免命名冲突(C语言中没有命名空间概念)[^1] #### 2. **类声明** ```cpp namespace MyLib { class Calculator { // 类定义 public: int add(int a, int b); // 成员函数声明 }; } ``` - `Calculator` 是自定义类类型 - 包含成员函数 `add()`(实现略) #### 3. **对象实例化** - `calc` 是 `Calculator` 类的具体**对象** - 实例化过程: 1. 编译器分配内存空间(通常位于上) 2. 调用默认构造函数(隐式生成) 3. 创建完整的对象状态 #### 4. 内存模型示意 ```mermaid classDiagram namespace MyLib { class Calculator { -内存地址: 0x7ffd... +add(int a, int b) } } Calculator <|-- calc : 实例化 ``` #### 5. 使用示例 ```cpp int main() { MyLib::Calculator calc; // 实例化对象 int result = calc.add(3, 5); // 调用成员函数 // 对象在上分配 std::cout << "对象地址: " << &calc; // 如 0x7ffd... } ``` #### 关键特性总结 | 概念 | 说明 | |------|------| | **`MyLib::`** | 命名空间限定符(避免全局命名冲突) | | **`Calculator`** | 用户自定义类类型(蓝图) | | **`calc`** | 类的具体实例(内存中的对象) | | **生命周期** | 自动管理(离开作用域时自动销毁) | | **内存位置** | 通常位于内存(除非使用`new`) | > 当执行 `MyLib::Calculator calc;` 时,编译器: > 1. 检查 `MyLib` 命名空间是否存在 > 2. 验证 `Calculator` 类是否可实例化 > 3. 在上分配 `sizeof(Calculator)` 字节内存 > 4. 调用构造函数初始化对象状态 > 5. 将标识符 `calc` 绑定到该内存地址
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值