【Daily Code】leetcode 2182. 构造限制重复的字符串

Problem: 2182. 构造限制重复的字符串

Code

C++ 复制代码
class Solution {
public:
    static bool cmp(pair<char, int>& l, pair<char, int>& r)
    {
        // 如果value相等,比较key值
        if (l.first == r.first)
            return l.second > r.second;
        else
        // 否则比较value值
            return  l.first > r.first;
    }
    string repeatLimitedString(string s, int repeatLimit) {
        // 感觉找一个合适的数据结构还挺重要
        unordered_map<char, int> cnt;
        for(auto x: s) {
            cnt[x] ++;
        }
        vector<pair<char, int>> result(cnt.begin(), cnt.end());
        sort(result.begin(), result.end(), cmp);
        string res = "";
        int l = result.size();
        int i = 0;
        while(i < l) {
            int x =  result[i].first, y =  result[i].second;
            if(y <= repeatLimit) {
                res.append(y, x);
                result[i ++ ].second = 0;
            }
            else {
                // 特判:防止出现repeatLimit == 1,结尾是bbbb这种情况
                int len = res.size();
                if( len > 0 && res[len - 1] == x) break;
                res.append(repeatLimit, x);
                result[i].second -= repeatLimit;
                if(i == l - 1) break;

                int j = i + 1;
                for(j; j < l; j ++) {
                    if(result[j].second > 0 ) {
                        res.append(1, result[j].first);
                        result[j].second --;
                        break;
                    }
                }
            }
        }
        return res;
    }
};
相关推荐
清酒难咽3 小时前
算法案例之递归
c++·经验分享·算法
让我上个超影吧4 小时前
【力扣26&80】删除有序数组中的重复项
算法·leetcode
张张努力变强5 小时前
C++ Date日期类的设计与实现全解析
java·开发语言·c++·算法
沉默-_-5 小时前
力扣hot100滑动窗口(C++)
数据结构·c++·学习·算法·滑动窗口
钱彬 (Qian Bin)5 小时前
项目实践19—全球证件智能识别系统(优化检索算法:从MobileNet转EfficientNet)
算法·全球证件识别
feifeigo1235 小时前
基于EM算法的混合Copula MATLAB实现
开发语言·算法·matlab
漫随流水5 小时前
leetcode回溯算法(78.子集)
数据结构·算法·leetcode·回溯算法
IT猿手6 小时前
六种智能优化算法(NOA、MA、PSO、GA、ZOA、SWO)求解23个基准测试函数(含参考文献及MATLAB代码)
开发语言·算法·matlab·无人机·无人机路径规划·最新多目标优化算法
We་ct6 小时前
LeetCode 151. 反转字符串中的单词:两种解法深度剖析
前端·算法·leetcode·typescript
芜湖xin6 小时前
【题解-Acwing】AcWing 5579. 增加模数(TLE)
算法·快速幂