【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;
    }
};
相关推荐
203号居民31 分钟前
LeetCode hot 100 —560. 和为 K 的子数组
java·算法·leetcode
退休倒计时1 小时前
【每日一题】LeetCode 20. 有效的括号 TypeScript
算法·leetcode·职场和发展·typescript
文心快码BaiduComate1 小时前
光本位联合文心快码打造面向光电芯片研发的全栈AI Agent Lightmate
算法
一次旅行1 小时前
ViT/CLIP/LLaVA/GPT-4V/VideoLLM多模态架构全解:原理仿真+工业落地选型+完整推理代码
人工智能·算法·架构
神明不懂浪漫2 小时前
【第五章】队列
开发语言·数据结构·经验分享·笔记·算法
happy_baymax2 小时前
MATLAB MCP Server+ MATLAB Agentic Toolkit+Simulink Agentic Toolkit自动更新批处理文件.ps1
人工智能·算法
神明不懂浪漫2 小时前
【第六章】二叉树
开发语言·数据结构·经验分享·笔记·算法
橘和柠3 小时前
知识图谱实战(一):数据采集与实体关系抽取(完整代码)
算法
Mem0rin3 小时前
前缀和:中心下标与数组乘积
数据结构·算法
windliang3 小时前
Claude Code 源码分析(八):Memory 如何被写入、整理与按需召回
前端·算法·面试