【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;
    }
};
相关推荐
MrZhao4002 分钟前
On-Policy Distillation(OPD):为什么大模型后训练要在学生自己的轨迹上蒸馏?
算法
朱峥嵘(朱髯)12 分钟前
数据库如何根据全表 NDV 估算子集的 NDV
数据库·算法
jjjava2.020 分钟前
牛客算法题(第四期)
算法
雪碧聊技术22 分钟前
力扣 回溯法 | LCR 020. 回文子串
javascript·算法·leetcode
wabs66627 分钟前
关于哈希表【力扣454.四数相加II的思考】
数据结构·算法·leetcode·散列表
我能坚持多久40 分钟前
优选算法——专题一双指针(上):附四道例题详解
c++·学习·算法
Forever Nore42 分钟前
LeetCode 2 两数相加 - 链表
leetcode·链表·哈希表
Tim_101 小时前
【C++】023、移动语义&深拷贝
开发语言·c++·算法
月光船幽幽1 小时前
锁死后干预有效性的关键突破
人工智能·python·算法
2501_906565121 小时前
哥德巴赫猜想
算法