[LeetCode] Longest Happy String

1405. Longest Happy String

A string s is called happy if it satisfies the following conditions:

  • s only contains the letters ‘a’, ‘b’, and ‘c’.
  • s does not contain any of “aaa”, “bbb”, or “ccc” as a substring.
  • s contains at most a occurrences of the letter ‘a’.
  • s contains at most b occurrences of the letter ‘b’.
  • s contains at most c occurrences of the letter ‘c’.

Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string “”.

A substring is a contiguous sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string longestDiverseString(int a, int b, int c, char ca = 'a', char cb = 'b', char cc = 'c') {
if(a < b)
return longestDiverseString(b,a,c,cb,ca,cc);
if(b < c)
return longestDiverseString(a,c,b,ca,cc,cb);
if(b == 0)
return string(min(a,2),ca);

int aa = min(a,2), bb = a - aa >= b ? 1 : 0;
return string(aa,ca) + string(bb,cb) + longestDiverseString(a-aa,b-bb,c,ca,cb,cc);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/03/PS/LeetCode/longest-happy-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.