题目链接:1405. 最长快乐字符串
贪婪。每次从剩余最多的字母开始尝试,若剩余最多的字母不可用,则使用剩余第二多的字母,直到没有可用字母。
Note: 没有要求必须把所有字母都用完。
class Solution:
def longestDiverseString(self, a: int, b: int, n_ch: int) -> str:
ret, q = [], [[a, 'a'], [b, 'b'], [n_ch, 'c']]
while True:
q.sort(reverse=True)
has_next = False
for i, (n_ch, ch) in enumerate(q):
if n_ch <= 0:
break
if len(ret) >= 2 and ret[-2] == ret[-1] == ch:
continue
has_next = True
ret.append(ch)
q[i][0] -= 1
break
if not has_next:
return ''.join(ret)