358. Rearrange String k Distance Apart
這道題就是把所有值都進(jìn)行最大區(qū)分瞎抛,在重新加入heap的時(shí)候要注意器躏,如果兩個(gè)值有同樣的count些己,那么后訪問過的要先加進(jìn)去,比如說bba, size=1炭剪,先加入b辉阶,此時(shí)a,b的count都是1先壕,這時(shí)候要先加入a,再加入b
class Solution(object):
def rearrangeString(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
if k == 0:
return s
h = {}
for c in s:
h[c] = h.get(c, 0) + 1
heap = []
for key, val in h.iteritems():
heapq.heappush(heap, [-val, key])
res = []
while heap:
temp = []
n = len(s) - len(res)
for _ in range(min(k, n)):
if not heap:
return ""
cur_val, key = heapq.heappop(heap)
res.append(key)
cur_val += 1
if cur_val != 0:
temp.append([cur_val, key])
while temp:
heapq.heappush(heap, temp.pop())
return "".join(res)