题目描述:
如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。
给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:
s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
s 中只含有 'a'、'b' 、'c' 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 ""。
样例:
方法一:
class Solution {
public:
static bool compare(pair<int, char>& p1, pair<int, char>& p2)
{
return p1.first > p2.first;
}
string longestDiverseString(int a, int b, int c) {
vector<pair<int, char>> prique = {{a, 'a'}, {b, 'b'}, {c, 'c'}};
string ans;
while (1)
{
//每次循环时先排序一遍,即优先队列的用法
sort(prique.begin(), prique.end(), compare);
int n = ans.size();
for (auto& [cnt, ch] : prique)
{
if (cnt <= 0) break;
//避免出现三个连续的相同的字母
if (n >= 2 && ans[n - 1] == ch && ans[n - 2] == ch) continue;
ans.push_back(ch);
cnt--;
break;
}
//如果字符串已经不能再添加新的字母了,退出
if (ans.size() == n) break;
}
return ans;
}
};
很好懂的题目,也容易想到贪心和优先队列,但是我贪不出来啊。。
我自己写的时候优先队列用的是priority_queue,但是priority_queue容器很难进行遍历,所以当发现队首的字母不能够使用时,如果要用后续的字母,那么挺不好操作的。
而如果用vector的话,就可以解决遍历容器的问题了,只需在每次遍历时先排序一遍,就能够实现优先队列的功能了,这倒是一个很好的想法!