题目链接:1405. 最长快乐字符串
题意:
如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。
给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:
s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
s 中只含有 'a'、'b' 、'c' 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 ""。
方法: 优先队列+贪心算法
利用大根堆和pair,每次插入的时候排序按照字符个数从大到小排序,相等的情况下,按照字典序从大到小排序。每一次从队列中读取前两个pair对,假设当前pair中的字符会出现重复使用的情况,就使用另一个pair中的字符。
贪心的情况分为当前字符是最多的,或者不是最多的,假如是最多的,我们希望尽量多的使用该字符,如果不是最多的,尽量少使用,即使用一个,目的是为了使每个字符的字符数量趋于相等。
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
string ans = "";
char pre = ' ';
priority_queue<pair<int,char>,vector<pair<int,char>>,less<pair<int,char>>> q;
q.push(make_pair(a,'a'));
q.push(make_pair(b,'b'));
q.push(make_pair(c,'c'));
while(!q.empty()){
auto first = q.top();q.pop();
auto second = q.top();q.pop();
int cnt1 = first.first;
int cnt2 = second.first;
char ch1 = first.second;
char ch2 = second.second;
if(ch1==pre){
if(cnt2==0){
return ans;
} else{
pre = ch2;
ans += ch2;
cnt2 -= 1;
}
}else{
if(cnt1==0){
return ans;
} else if(cnt1==1){
pre = ch1;
ans += ch1;
cnt1 -= 1;
} else{
pre = ch1;
ans += ch1;
ans += ch1;
cnt1 -= 2;
}
}
q.push(make_pair(cnt1,ch1));
q.push(make_pair(cnt2,ch2));
}
return ans;
}
};