【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;
    }
};
相关推荐
爱思德学术5 小时前
中国计算机学会(CCF)推荐学术会议-B(计算机体系结构/并行与分布计算/存储系统):SPAA 2026
算法
5 小时前
2.12矩阵问题,发牌,数字金字塔
线性代数·算法·矩阵
无聊的小坏坏5 小时前
一文讲通:二分查找的边界处理
数据结构·c++·算法
m0_528749005 小时前
C语言错误处理宏两个比较重要的
java·linux·算法
TracyCoder1235 小时前
LeetCode Hot100(50/100)——153. 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
诸葛务农5 小时前
点云配准在人形机器人中的应用:ICP算法(2)
人工智能·算法·机器学习·机器人
摘星编程6 小时前
**解锁Agent智能体新纪元:自主协作、任务分解与人类意图对齐的终极指南**
算法
mmz12076 小时前
逆序对问题(c++)
c++·算法
化学在逃硬闯CS6 小时前
Leetcode110.平衡二叉树
数据结构·c++·算法·leetcode
谢铭轩6 小时前
题解:P8035 [COCI 2015/2016 #7] Otpor
c++·算法