这题参考了讨论区的大神Priyan的思路。具体而言,对于字符和数量的tuple,每一轮添加到res后,都做排序,当一开始做添加字符,res不到2个字符长度时,添加最多的字符。当长于两个字符且res的后两位字符一样且与最多字符一致时,添加目前第二多的字符。当目前(无论添加最多的还是第二多的字符)所需要的字符为0时,则说明要么完全添加完了,字符库空了。或者还有字符,但是不能添加,因为会造成happy string。
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
warehouse = [['a',a], ['b',b], ['c',c]]
res = ''
while True:
warehouse.sort(key = lambda x:x[1])
if len(res) >= 2 and res[-1] == res[-2] == warehouse[2][0]:
char_index = 1
else:
char_index = 2
if warehouse[char_index][1] != 0:
res += warehouse[char_index][0]
warehouse[char_index][1] -= 1
else:
break
return res