Leetcode 1405. Longest Happy String (python)

这篇博客探讨了LeetCode第1405题——最长快乐字符串的解决方案。作者采用贪心策略,每次选择出现次数最多的字符,并确保不连续出现相同的字符。通过使用最大堆来维护字符选择顺序,实现了问题的高效解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

在这里插入图片描述

解法

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

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值