当前位置: 代码迷 >> 综合 >> Leetcode 1405. Longest Happy String (python)
  详细解决方案

Leetcode 1405. Longest Happy String (python)

热度:73   发布时间:2023-11-26 06:19:07.0

题目

在这里插入图片描述

解法

贪心思想。每次取个数最多的来加,同时判断前两个是否相同。利用最大堆保持顺序。

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
  相关解决方案