1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
reorganize-string.py 917 Bytes
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 7年前 . add complexity
# Time: O(nloga) = O(n), a is the size of alphabet
# Space: O(a) = O(1)
import collections
import heapq
class Solution(object):
def reorganizeString(self, S):
"""
:type S: str
:rtype: str
"""
counts = collections.Counter(S)
if any(v > (len(S)+1)/2 for k, v in counts.iteritems()):
return ""
result = []
max_heap = []
for k, v in counts.iteritems():
heapq.heappush(max_heap, (-v, k))
while len(max_heap) > 1:
count1, c1 = heapq.heappop(max_heap)
count2, c2 = heapq.heappop(max_heap)
if not result or c1 != result[-1]:
result.extend([c1, c2])
if count1+1: heapq.heappush(max_heap, (count1+1, c1))
if count2+1: heapq.heappush(max_heap, (count2+1, c2))
return "".join(result) + (max_heap[0][1] if max_heap else '')
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助