leetcode 1405 最长快乐字符串

题意

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

给你三个整数 aabbcc,返回任意一个满足下列全部条件的字符串 ss

ss 是一个尽可能长的快乐字符串。

ss 中最多有 aa 个字母’a’、bb个字母 ‘b’、cc 个字母 ‘c’ 。

ss 中只含有 ‘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;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!