题意
如果字符串中不含有任何 ‘aaa’,‘bbb’ 或 ‘ccc’ 这样的字符串作为子串,那么该字符串就是一个快乐字符串。
给你三个整数 a,b ,c,返回任意一个满足下列全部条件的字符串 s:
s 是一个尽可能长的快乐字符串。
s 中最多有 a 个字母’a’、b个字母 ‘b’、c 个字母 ‘c’ 。
s 中只含有 ‘a’、‘b’ 、‘c’ 三种字母。
做法
优先选用当前数量最多的字母,如果重复,往下继续找。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public: string longestDiverseString(int a, int b, int c) { string res; vector<pair<int, char>> arr = {{a, 'a'}, {b, 'b'}, {c, 'c'}}; while (true) { sort(arr.begin(), arr.end(), greater<pair<int, char>>()); bool hasNext = false; for (auto & [freq, ch] : arr) { int m = res.size(); if (freq <= 0) { break; } if (m >= 2 && res[m - 2] == ch && res[m - 1] == ch) { continue; } hasNext = true; res.push_back(ch); freq--; break; } if (!hasNext) { break; } } return res; } };
|