Leetcode Basic Calculator

题意:编写一个基本的计算器,实现加减法操作。

思路:用堆栈完成优先级操作。

class Solution {
public:
    int calculate(string s) {
        stack<char> cal;
        for(int i = 0; i < s.length(); ++ i) {
            if(s[i] == ' ') continue;
            if(s[i] ==')') {
                string temp;
                while(cal.top() != '(') {
                    temp +=cal.top();
                    cal.pop();
                }
                cal.pop();
                std::reverse(temp.begin(), temp.end());
               // cout << temp << endl;
                
                temp = re(temp);
                //cout << temp << endl;
                for(int i = 0; i < temp.length(); ++ i) cal.push(temp[i]);
            }
            else cal.push(s[i]);
        }
        string c;
        while(!cal.empty()) {
            if(cal.top() == '(' || cal.top() == ')') continue;
            c += cal.top();
            cal.pop();
        }
        //cout << c << endl;
        std::reverse(c.begin(), c.end());
        if(c[0] == '+') return std::stoi(c.substr(1));
        if(c[0] == '-') return -std::stoi(c.substr(1));
        
        
        c = re(c);
        
        return std::stoi(c);
    }
    
    string re(string s) {
        vector<string> nums;
        vector<char> op;
        string temp;
        for(int i = 0; i < s.length()- 1; ++ i) {
            if(s[i] == '+' && (s[i + 1] == '-' || s[i + 1] == '+')) s[i] = ' ';
            if(s[i] == '-' && s[i + 1] == '+') s[i + 1] = ' ';
            if(s[i] == '-' && s[i + 1] == '-') {
                s[i] = ' ';
                s[i + 1] = '+';
            }
        }
        for(int i = 0; i < s.length(); ++ i) {
            if(s[i] == ' ') continue;
            if(s[i] == '+' || s[i] == '-') {
                op.push_back(s[i]);
                nums.push_back(temp);
                temp = "";
            }
            else temp += s[i];
        }
        if(temp.length()) nums.push_back(temp);
        
        if(op.size() == 0) return s;
        if(nums.size() - op.size() != 1) return s;
        
        int sum = std::stoi(nums[0]);
        for(int i = 0; i < op.size(); ++ i) {
            if(op[i] == '+') sum += std::stoi(nums[i + 1]);
            if(op[i] == '-') sum -= std::stoi(nums[i + 1]);
        }
        return to_string(sum);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值