193、【栈与队列】leetcode ——面试题 16.26. 计算器(C++版本)

题目描述

在这里插入图片描述

Problem: 面试题 16.26. 计算器

思路

采取双栈的形式,分为操作数栈和运算符栈。

解题方法

对于操作数,遍历到一个数就压入,需要进行操作时,再弹出。对于运算符,当栈中元素为空或者遍历元素比栈中元素优先级小的话,只压入栈。若遍历元素比栈中元素优先级大的化,则先对栈中元素进行运算操作,然后再压入栈。最后结尾,若运算符栈非空或者操作数栈中个数不为1,则是因为最后一个压入元素没有进行运算,对剩余元素进行操作。

复杂度

  • 时间复杂度:

添加时间复杂度, 示例: O ( n ) O(n) O(n)

  • 空间复杂度:

添加空间复杂度, 示例: O ( n ) O(n) O(n)

Code


class Solution {
public:
    int calculate(string s) {
        stack<int> operands;
        stack<int> operators;
        int i = 0;
        while (i < s.size()) {
            // 处理空格
            if(s[i] == ' ') {
                while(s[i] == ' ') {
                    i++;
                }    
            // 取数字
            } else if(isdigit(s[i])) {
                int num = 0;
                // 从个位到高位依次取数构造
                for(; i < s.size() && isdigit(s[i]); i++) {
                    num = num * 10 + (s[i] - '0');
                }
                operands.push(num);
            // 取运算符
            } else {
                // 运算符栈中不为空时,让栈顶元素和s[i]进行比较,如果s[i]的优先级低,则让栈顶元素先操作。
                while(!operators.empty() && !priority(s[i], operators.top())){                    
                    calc(operands, operators);
                }
                operators.push(s[i]);
                i++;
            }
        }
        while(!operators.empty()) {
            calc(operands, operators);
        }

        return operands.top();
    }

    void calc(stack<int>& operands, stack<int>& operators) {
        int b = operands.top();             operands.pop();
        int a = operands.top();             operands.pop();
        int op = operators.top();           operators.pop();
        int res = 0;
        switch(op) {
            case '+' : res = a + b;     break;
            case '-' : res = a - b;     break;
            case '*' : res = a * b;     break;
            case '/' : res = a / b;     break;
            default  : ;
        }
        operands.push(res);

        return ;
    }

    // a的优先级是否高于b
    bool priority(int a, int b) {
        // a为加减一类,则已经为最低一类级别优先级,返回false
        if(a == '+' || a == '-') {
            return false;
        // a为乘除一类,则优先级更高
        } else if (a == '*' || a == '/') {
            // 当b比a优先级低时,返回true。同级,则返回false
            return (b == '+' || b == '-');
        }

        return false;
    }
};

参考文章:双栈算法面试题 16.26. 计算器(C++ 「栈+辅助栈」【图解】)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰阳星宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值