题解 | 计算器(二)

计算器(二)

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

class Solution {
public:
  //对加法乘除进行优先级的标号
    unordered_map<char, int> order = {
        {'+', 1},
        {'-', 1},
        {'*', 2},
        {'/', 2}
    };

    int calculate(string s) { 
	  //使用两个栈分别存储数字和运算符;
        stack<int> nums;
        stack<char> ops;
        int n = 0;
        bool parsingNumber = false;
		
		//遇到数字进行构造数字,遇到符号进行计算,先计算栈中优先级高或相等的运算符,
		//栈中最多两个运算符,
        for(int i=0; i<s.size(); ++i){
            char c = s[i];

            if(isdigit(c)){
                n = n*10 + (c - '0'); //字符转数字
                parsingNumber = true;
            }

            if(!isdigit(c)  || i==s.size()-1){
                if(parsingNumber){  //数字进栈
                    nums.push(n);
                    n = 0;
                    parsingNumber = false;
                }

                if(i < s.size()-1 || !isdigit(c)){ //计算栈中保留的运算
                    while(!ops.empty() && order[ops.top()] >= order[c]){
                        compute(nums, ops);
                    }
                    ops.push(c);
                }
            }
        }

        while(!ops.empty()){ //可能包含存在
            compute(nums, ops);
        }

        return nums.top();
    }
  
private:
    void compute(stack<int>& nums, stack<char>& ops){
        int b = nums.top(); nums.pop();
        int a = nums.top(); nums.pop();
        char op = ops.top(); ops.pop();

        switch (op) {
            case '+':nums.push(a+b);break;
            case '-':nums.push(a-b);break;
            case '*':nums.push(a*b);break;
            case '/':nums.push(a/b);break;
        }
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-26 18:18
点赞 评论 收藏
分享
06-15 18:44
黄淮学院 Java
Lynn012:如果是居民楼还是算了吧,看着有点野呢
点赞 评论 收藏
分享
叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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