题目
解法
贪心思想。每次取个数最多的来加,同时判断前两个是否相同。利用最大堆保持顺序。
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 orderh = []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 countcnt,c = heapq.heappop(h)cnt = -cnt# if the current category cannot be added anymore, pop out the category with the second max countif len(ans)>=2 and ans[-1]==ans[-2]==c:if h:sec_cnt,sec_c = heapq.heappop(h)sec_cnt = -sec_cntans += sec_csec_cnt -= 1if sec_cnt:heapq.heappush(h,(-sec_cnt,sec_c))else:return ans# else, simply add the char from the category with max countelse:cnt -= 1ans += c# always remember to push it back when there is still chat to use for every categoryif cnt:heapq.heappush(h,(-cnt,c))return ans