【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;
    }
};
相关推荐
AD钙奶-lalala几秒前
leetcode核心母题总结
算法·leetcode·职场和发展
YGGP13 分钟前
【Golang】LeetCode 2. 两数相加
开发语言·leetcode·golang
努力学算法的蒟蒻15 分钟前
day53(1.4)——leetcode面试经典150
算法·leetcode·面试
leiming618 分钟前
c++ transform算法
开发语言·c++·算法
裴云飞29 分钟前
Compose原理一之快照系统
算法·架构
橘颂TA30 分钟前
【剑斩OFFER】哈希表简介
数据结构·算法·散列表
小尧嵌入式31 分钟前
c++红黑树及B树B+树
开发语言·数据结构·c++·windows·b树·算法·排序算法
tobias.b36 分钟前
408真题解析-2009-10-数据结构-排序
数据结构·算法·排序算法·408考研·408真题·真题解析
Zachary_zlc40 分钟前
有向无环图检测算法和关键路径算法
算法
你撅嘴真丑41 分钟前
素数回文数的个数 与 求分数序列和
算法