LeetCode-1405 最长最快乐字符串

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-happy-string

题目描述

如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。

给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:

s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
s 中只含有 'a'、'b' 、'c' 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 ""。

 

示例 1:

输入:a = 1, b = 1, c = 7
输出:"ccaccbcc"
解释:"ccbccacc" 也是一种正确答案。


示例 2:

输入:a = 2, b = 2, c = 1
输出:"aabbc"


示例 3:

输入:a = 7, b = 1, c = 0
输出:"aabaa"
解释:这是该测试用例的唯一正确答案。
 

提示:

0 <= a, b, c <= 100
a + b + c > 0

 

解题思路

使用贪心的算法思路,每次希望将最多的字母输入字符串,所以首先判断是否将最多字母输入字符串会构成快乐字符串,如果不是那么输入,如果会构成,那么输入第二多的字母,直到所有字母都使用或者无法构成非快乐字符串。

代码展示

复制代码
class Solution {
public:
    string longestDiverseString(int a, int b, int c) {
        string strRet;
        auto cmp = [&](const auto &a, const auto &b) {
            return a.second < b.second;
        };
        priority_queue<pair<char, int>, vector<pair<char, int>>, decltype(cmp)> pqueueQ(cmp);
        if (a)
            pqueueQ.push({ 'a', a });
        if (b)
            pqueueQ.push({ 'b', b });
        if (c)
            pqueueQ.push({ 'c', c });
        char cLast = 'd'; int iCount = 0;
        while (!pqueueQ.empty())
        {
            auto top = pqueueQ.top();
            if (top.first == cLast && iCount == 1)
            {
                if (pqueueQ.size() == 1)
                    break;
                pqueueQ.pop();
                auto top2 = pqueueQ.top();
                strRet.push_back(top2.first);
                top2.second--;
                pqueueQ.pop();
                if (top2.second)
                {
                    pqueueQ.push(top2);
                }
                pqueueQ.push(top);
                if (cLast == top2.first)
                {
                    iCount++;
                }
                else
                {
                    iCount = 0;
                }
                cLast = top2.first;
            }
            else
            {
                pqueueQ.pop();
                strRet.push_back(top.first);
                top.second--;
                if (top.second)
                {
                    pqueueQ.push(top);
                }
                if (cLast == top.first)
                {
                    iCount++;
                }
                else
                {
                    iCount = 0;
                }
                cLast = top.first;
            }

        }
        return strRet;
    }
};
复制代码

 

运行结果

 

posted @   过客匆匆,沉沉浮浮  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示