1405. Longest Happy String
Description
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 mosta
occurrences of the letter'a'
.s
contains at mostb
occurrences of the letter'b'
.s
contains at mostc
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.
Example 1:
Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It is the only correct answer in this case.
Constraints:
0 <= a, b, c <= 100
a + b + c > 0
Solution
longest-happy-string.py
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
size = a + b + c
A, B, C = 0, 0, 0
res = ""
for i in range(size):
if (a >= b and a >= c and A != 2) or (B == 2 and a > 0) or (C == 2 and a > 0):
res += "a"
a -= 1
A += 1
B = 0
C = 0
elif (b >= a and b >= c and B != 2) or (A == 2 and b > 0) or (C == 2 and b > 0):
res += "b"
b -= 1
B += 1
A = 0
C = 0
elif (c >= a and c >= b and C != 2) or (A == 2 and c > 0) or (B == 2 and c > 0):
res += "c"
c -= 1
C += 1
A = 0
B = 0
return res