0% found this document useful (0 votes)
8 views

Longest Happy String

Uploaded by

hatshthegreat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Longest Happy String

Uploaded by

hatshthegreat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solution {

public:
string longestDiverseString(int a, int b, int c) {
string res = "";
vector<pair<int, char>> counts = {{a, 'a'}, {b, 'b'}, {c, 'c'}};

while (true) {
// Sort counts in descending order by the number of occurrences
sort(counts.rbegin(), counts.rend());

bool added = false;


for (auto &[count, ch] : counts) {
if (count <= 0) continue;

int n = res.size();
// If the last two characters in the result are the same as the
current character, skip this character for now
if (n >= 2 && res[n - 1] == ch && res[n - 2] == ch) continue;

// Add the character and decrease its count


res += ch;
count--;
added = true;
break;
}

if (!added) break; // No more characters can be added without violating


the rules
}

return res;
}
};

You might also like