# 【LeetCode】358. Rearrange String k Distance Apart 解题报告（Python）

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

## 题目描述：

Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other.

All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".

Example 1:

str = " ", k = 3

Result: "abcabc"

The same letters are at least distance 3 from each other.


Example 2:

str = "aaabc", k = 3

It is not possible to rearrange the string.


Example 3:

str = "aaadbbcc", k = 2

The same letters are at least distance 2 from each other.


## 解题方法

class Solution:
def rearrangeString(self, words, k):
_len = len(words)
words_count = collections.Counter(words)
que = []
heapq.heapify(que)
for w, v in words_count.items():
heapq.heappush(que, (-v, w))
res = ""
while que:
cnt = min(_len, k)
used = []
for i in range(cnt):
if not que:
return ""
v, w = heapq.heappop(que)
res += w
if -v > 1:
used.append((v + 1, w))
_len -= 1
for use in used:
heapq.heappush(que, use)
return res


http://www.cnblogs.com/grandyang/p/5586009.html

## 日期

2018 年 10 月 13 日 —— 这个题没有用OJ测试

• 0
点赞
• 1
收藏
• 打赏
• 0
评论
04-26 3806
10-14 278
07-11 133
02-26 133
07-22 1527
09-04 609
10-31 240
04-06 514

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

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

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