【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;
    }
};
相关推荐
沐苏瑶7 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
ZoeJoy88 小时前
算法筑基(二):搜索算法——从线性查找到图搜索,精准定位数据
算法·哈希算法·图搜索算法
Alicx.8 小时前
dfs由易到难
算法·蓝桥杯·宽度优先
_日拱一卒8 小时前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
云泽8089 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享9 小时前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病9 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中11 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy11 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl2002092511 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划