其他分享
首页 > 其他分享> > 1405. 最长快乐字符串

1405. 最长快乐字符串

作者:互联网

题目描述

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-happy-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

算法分析

总体来说利用贪心的方法进行操作
将a,b,c的个数进行排序
每次从三者中最多的提取出一个记为char

我们可以采用priority_queue进行排序以及动态维护最多和次多的字母(priority_queue<pair<int, int> > pq;)
然后不断的从pq中找出最大的次大的,加入后减少次数并判断是否减为0,假如减为0则pop出队列
当队列为空则程序结束

参考代码

class Solution {
public:
    string longestDiverseString(int a, int b, int c) {
        string ans;
        priority_queue<pair<int, int> > pq;
        if(a) pq.push({a,0}); // 插入a,b,c的个数
        if(b) pq.push({b,1});
        if(c) pq.push({c,2});
        while(!pq.empty()){
            pair<int,int> first=pq.top();
            pq.pop();
            if (ans.size() >= 2 && first.second + 'a' == ans[ans.size() - 1] && first.second + 'a' == ans[ans.size() - 2]) {
            //首先判断ans的长度,再判断ans的尾是否为pd.top(),再判断ans的次尾是否为pd.top(),如果都符合则应该插次多在最尾
                if (pq.empty()) break;
                pair<int,int> second=pq.top();
                pq.pop();
                ans +=  ('a' + second.second);
                second.first -= 1;
                if (second.first != 0 )//判断是否个数为0
                    pq.push(second);
                pq.push(first);
            }
            else{//插入最多的一个字符
                ans += ('a' + first.second);
                first.first -= 1;
                if (first.first != 0 )//判断是否个数为0
                    pq.push(first);
            }
        }
        return ans;
    }
};

在这里插入图片描述

标签:pq,push,second,快乐,ans,字符串,1405,first
来源: https://blog.csdn.net/qq_38780760/article/details/122813346