原题链接:https://leetcode-cn.com/problems/longest-happy-string/
贪心算法
class Solution {
public:
static bool greater(const pair<char, int>& a, const pair<char, int>& b) {
return a.second > b.second;
}
string longestDiverseString(int a, int b, int c) {
string res;
vector<pair<char, int>> vec = {{'a', a}, {'b', b}, {'c', c}};
int i = 0;
while (res.size() < a+b+c) {//每次循环均排序,vec[0]是剩余最多的,vec[1]是次多的
sort(vec.begin(), vec.end(), greater);
if (res.size() && res.back() == vec[0].first) {//如果剩余最多的,与上次选取的重复,则选取次多的。次多的一定不会与上次重复
if (vec[1].second--) res += vec[1].first;
else break;
} else {//每次从剩余最多的中选取两个
if (vec[0].second--) res += vec[0].first;
if (vec[0].second--) res += vec[0].first;
}
}
return res;
}
};