问题描述
思路分析及代码实现
贪心
动态获取当前剩余字符中数量最多的和次多的字符
先尽可能的使用数量最多的字符,
如果不满足条件再使用次多的字符,因为只有三种字符,所以每次只会在数量最多和次多中选择,
当所有字母使用完之后,仍无法满足条件就可以跳出while循环了。
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
count = {'a': a, 'b': b, 'c': c}
res = ''
while True:
_, mid, most = sorted(count.keys(), key = lambda x: count[x])
if (len(res) < 2 or not res[-2]==res[-1]==most) and count[most]:
res += most
count[most] -= 1
elif count[mid]:
res += mid
count[mid] -= 1
else:
break
return res