【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;
    }
};
相关推荐
17(无规则自律)4 分钟前
C++ 链表修炼指南
数据结构·c++·算法·leetcode·链表
KhalilRuan5 分钟前
基于OpenGL实现布料模拟
算法
大江东去浪淘尽千古风流人物6 分钟前
【claw】 OpenClaw 的架构设计探索
深度学习·算法·3d·机器人·slam
闻缺陷则喜何志丹6 分钟前
【字典树 回溯】P7210 [COCI 2020/2021 #3] Vlak|普及+
c++·算法·字典树·回溯·洛谷
夏玉林的学习之路7 分钟前
委托构造和using关键字
开发语言·c++·算法
small-pudding8 分钟前
深入理解PDF:蒙特卡洛光线追踪中的概率密度函数
算法·pdf·图形渲染
We་ct11 分钟前
LeetCode 46. 全排列:深度解析+代码拆解
前端·数据结构·算法·leetcode·typescript·深度优先·回溯
逆境不可逃11 分钟前
LeetCode 热题 100 之 763.划分字母区间
算法·leetcode·职场和发展
MicroTech202517 分钟前
微算法科技(NASDAQ:MLGO)量子PBFT改进技术:重构联盟链共识的效率与安全
科技·算法·重构
程序员小明儿18 分钟前
量子计算探秘:从零开始的量子编程与算法之旅 · 第二篇
算法·量子计算