如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。
给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:
s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
s 中只含有 'a'、'b' 、'c' 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 ""。
示例 1:
输入:a = 1, b = 1, c = 7
输出:"ccaccbcc"
解释:"ccbccacc" 也是一种正确答案。
示例 2:
输入:a = 2, b = 2, c = 1
输出:"aabbc"
示例 3:
输入:a = 7, b = 1, c = 0
输出:"aabaa"
解释:这是该测试用例的唯一正确答案。
提示:
0 <= a, b, c <= 100
a + b + c > 0
解析:
采用贪心的策略,每次选最长的字符(max(a, b, c))作为连续,然后取较少的作为中间分隔。
这样可以保证快乐字符串是最长。
#include<iostream>
#include<unordered_map>
using namespace std;
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
string str;
char ch;
unordered_map<char, int> mp;
mp['a'] = a;
mp['b'] = b;
mp['c'] = c;
ch = maxch(mp['a'], mp['b'], mp['c']);
while (mp[ch] != 0) {
construct(mp[ch], ch, str);
if (maxch(mp['a'], mp['b'], mp['c']) == ch) {
if (savech(ch, mp['a'], mp['b'], mp['c'], str)) {
ch = maxch(mp['a'], mp['b'], mp['c']);
continue;
}
else {
break;
}
}
else {
ch = maxch(mp['a'], mp['b'], mp['c']);
}
}
return str;
}
bool savech(char ch, int& a, int& b, int& c, string& str) {
bool issucc = true;
if (ch != 'a' && a > 0) {
str += 'a';
a--;
}
else if (ch != 'b' && b > 0) {
str += 'b';
b--;
}
else if (ch != 'c' && c > 0) {
str += 'c';
c--;
}
else {
issucc = false;
}
return issucc;
}
char maxch(int a, int b, int c) {
if (a >= b) {
if (a >= c) {
return 'a';
}
else {
return 'c';
}
}
else if (c >= b) {
return 'c';
}
else {
return 'b';
}
}
void construct(int& num, char c, string& str) {
if (num >= 2) {
num = num - 2;
str += c;
str += c;
}
else if (num == 1) {
num = num - 1;
str += c;
}
}
};
int main() {
Solution* ps = new Solution();
unique_ptr<Solution> ptr(new Solution());
cout << ps->longestDiverseString(7, 1, 0) << endl;
system("pause");
return 0;
}