【Leetcode每日一题】767. 重构字符串(大顶堆+贪心)

Leetcode每日一题
题目链接: 767. 重构字符串
难度: 中等
解题思路: 设置一个大顶堆,每次取出现最多的字符和次多的字符。将这两个字符排入结果。每次重构完后要重新将更新的字符数量push进入大顶堆,直到大顶堆为空。注意python的heapq是小顶堆,所有对字符出现的次数取负,可以实现大顶堆。
题解:

import heapq

class Solution:
    def reorganizeString(self, S: str) -> str:
        if len(S) < 2:
            return ""

        count = collections.Counter(S)
        # 只有一个元素且数量大于1
        if len(count) == 1 and len(S) > 1:
            return ""

        # 出现的次数取负,构建大顶堆
        queue = [(-x[1], x[0]) for x in count.items()]
        heapq.heapify(queue)


        res = ""
        while len(queue) > 1:
            # 出现次数最多和次多的
            _, c1 = heapq.heappop(queue)
            _, c2 = heapq.heappop(queue)
            res += c1 + c2

            # 出现次数减一
            count[c1] -= 1
            count[c2] -= 1

            # 重新构建大顶堆
            if count[c1] > 0:
                heapq.heappush(queue, (-count[c1], c1))
            if count[c2] > 0:
                heapq.heappush(queue, (-count[c2], c2)) 

        # print(count)
        print(queue)
        if queue:
            if (queue[0][0]) == -1:
                res += queue[0][1]
            else:
            	# 最后剩余的数量大于1,返回""
                return ""
        
        return res

            
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值