【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;
    }
};
相关推荐
dazzle1 小时前
机器学习算法原理与实践-入门(十一):基于PyTorch的房价预测实战
pytorch·算法·机器学习
小月球~9 小时前
天梯赛 · 并查集
数据结构·算法
仍然.9 小时前
算法题目---模拟
java·javascript·算法
6Hzlia10 小时前
【Hot 100 刷题计划】 LeetCode 118. 杨辉三角 | C++ 动态规划题解
c++·leetcode·动态规划
潇冉沐晴11 小时前
DP——背包DP
算法·背包dp
GIOTTO情11 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃12 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾12 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic12 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
副露のmagic12 小时前
字符串章节 leetcode 思路&实现
windows·python·leetcode