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