题目
解法
贪心思想。每次取个数最多的来加,同时判断前两个是否相同。利用最大堆保持顺序。
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
# main idea: use a greedy approach. Every time, try to take one char from the category with the maximum count. And use heap to maintain the order
h = []
if a>0:
heapq.heappush(h,(-a,'a'))
if b>0:
heapq.heappush(h,(-b,'b'))
if c>0:
heapq.heappush(h,(-c,'c'))
ans = ''
while h:
# pop out the category with max count
cnt,c = heapq.heappop(h)
cnt = -cnt
# if the current category cannot be added anymore, pop out the category with the second max count
if len(ans)>=2 and ans[-1]==ans[-2]==c:
if h:
sec_cnt,sec_c = heapq.heappop(h)
sec_cnt = -sec_cnt
ans += sec_c
sec_cnt -= 1
if sec_cnt:
heapq.heappush(h,(-sec_cnt,sec_c))
else:
return ans
# else, simply add the char from the category with max count
else:
cnt -= 1
ans += c
# always remember to push it back when there is still chat to use for every category
if cnt:
heapq.heappush(h,(-cnt,c))
return ans