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 = "aabbcc", k = 3

Result: "abcabc"

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

Example 2:

str = "aaabc", k = 3 

Answer: ""

It is not possible to rearrange the string.

Example 3:

str = "aaadbbcc", k = 2

Answer: "abacabcd"

Another possible answer is: "abcabcda"

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

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

给一个非空字符串和一个距离k,按k的距离间隔从新排列字符串,使得相同的字符之间间隔最少是k。

解法1:先用 HashMap 或者Array 对字符串里的字符按出现次数进行统计,按次数由高到低进行排序。出现次数最多的字符个数记为max_cnt,max_cnt - 1 是所需要的间隔数。把剩下字符按出现次数多的字符开始,把每一个字符插入到间隔中,以此类推,直到所有字符插完。然后判断每一个间隔内的字符长度,如果任何一个间隔<k,则不满足,返回"",如果都满足则返回这个新的字符串。

解法2:还是先统计字符出现的次数,按出现次数排列组成最大堆。然后每次从堆中去取topk 的字符排入结果,相应的字符数减1,如此循环,直到所有字符排完。

public class Solution {
public String rearrangeString(String str, int k) {
if (k <= 0) return str;
int[] f = new int[26];
char[] sa = str.toCharArray();
for(char c: sa) f[c-'a'] ++;
int r = sa.length / k;
int m = sa.length % k;
int c = 0;
for(int g: f) {
if (g-r>1) return "";
if (g-r==1) c ++;
}
if (c>m) return "";
Integer[] pos = new Integer[26];
for(int i=0; i<pos.length; i++) pos[i] = i;
Arrays.sort(pos, new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return f[pos[i2]] - f[pos[i1]];
}
});
char[] result = new char[sa.length];
for(int i=0, j=0, p=0; i<sa.length; i++) {
result[j] = (char)(pos[p]+'a');
if (-- f[pos[p]] == 0) p ++;
j += k;
if (j >= sa.length) {
j %= k;
j ++;
}
}
return new String(result);
}
}  

Python:  T: O(n) S: O(n)

class Solution(object):
def rearrangeString(self, str, k):
cnts = [0] * 26;
for c in str:
cnts[ord(c) - ord('a')] += 1 sorted_cnts = []
for i in xrange(26):
sorted_cnts.append((cnts[i], chr(i + ord('a'))))
sorted_cnts.sort(reverse=True) max_cnt = sorted_cnts[0][0]
blocks = [[] for _ in xrange(max_cnt)]
i = 0
for cnt in sorted_cnts:
for _ in xrange(cnt[0]):
blocks[i].append(cnt[1])
i = (i + 1) % max(cnt[0], max_cnt - 1) for i in xrange(max_cnt-1):
if len(blocks[i]) < k:
return "" return "".join(map(lambda x : "".join(x), blocks))

Python: T: O(nlogc), c is the count of unique characters. S: O(c)

from collections import defaultdict
from heapq import heappush, heappop
class Solution(object):
def rearrangeString(self, str, k):
if k == 0:
return str cnts = defaultdict(int)
for c in str:
cnts[c] += 1 heap = []
for c, cnt in cnts.iteritems():
heappush(heap, [-cnt, c]) result = []
while heap:
used_cnt_chars = []
for _ in xrange(min(k, len(str) - len(result))):
if not heap:
return ""
cnt_char = heappop(heap)
result.append(cnt_char[1])
cnt_char[0] += 1
if cnt_char[0] < 0:
used_cnt_chars.append(cnt_char)
for cnt_char in used_cnt_chars:
heappush(heap, cnt_char) return "".join(result)  

C++:

class Solution {
public:
string rearrangeString(string s, int k) {
if (k == 0) {
return s;
}
int len = s.size();
string result;
map<char, int> hash; // map from char to its appearance time
for(auto ch: s) {
++hash[ch];
}
priority_queue<pair<int, char>> que; // using priority queue to pack the most char first
for(auto val: hash) {
que.push(make_pair(val.second, val.first));
}
while(!que.empty()) {
vector<pair<int, int>> vec;
int cnt = min(k, len);
for(int i = 0; i < cnt; ++i, --len) { // try to pack the min(k, len) characters sequentially
if(que.empty()) { // not enough distinct charachters, so return false
return "";
}
auto val = que.top();
que.pop();
result += val.second;
if(--val.first > 0) { // collect the remaining characters
vec.push_back(val);
}
}
for(auto val: vec) {
que.push(val);
}
}
return result;
}
};

  

类似题目:

[LeetCode] 621. Task Scheduler 任务调度程序  

All LeetCode Questions List 题目汇总

[LeetCode] 358. Rearrange String k Distance Apart 按距离k间隔重排字符串的更多相关文章

  1. LeetCode 358. Rearrange String k Distance Apart

    原题链接在这里:https://leetcode.com/problems/rearrange-string-k-distance-apart/description/ 题目: Given a non ...

  2. 358. Rearrange String k Distance Apart

    /* * 358. Rearrange String k Distance Apart * 2016-7-14 by Mingyang */ public String rearrangeString ...

  3. 【LeetCode】358.K 距离间隔重排字符串

    358.K 距离间隔重排字符串 知识点:哈希表:贪心:堆:队列 题目描述 给你一个非空的字符串 s 和一个整数 k,你要将这个字符串中的字母进行重新排列,使得重排后的字符串中相同字母的位置间隔距离至少 ...

  4. [LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串

    Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...

  5. LC 358. Rearrange String k Distance Apart

    Given a non-empty string s and an integer k, rearrange the string such that the same characters are ...

  6. Levenshtein Distance莱文斯坦距离算法来计算字符串的相似度

    Levenshtein Distance莱文斯坦距离定义: 数学上,两个字符串a.b之间的莱文斯坦距离表示为levab(|a|, |b|). levab(i, j) = max(i, j)  如果mi ...

  7. 【LeetCode】358. Rearrange String k Distance Apart 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/rearrang ...

  8. 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

    [LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

  9. [LeetCode] 767. Reorganize String 重构字符串

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

随机推荐

  1. Tarjan算法分解强连通分量(附详细参考文章)

    Tarjan算法分解强连通分量 算法思路: 算法通过dfs遍历整个连通分量,并在遍历过程中给每个点打上两个记号:一个是时间戳,即首次访问到节点i的时刻,另一个是节点u的某一个祖先被访问的最早时刻. 时 ...

  2. P2602 [ZJOI2010]数字计数(递推)

    P2602 [ZJOI2010]数字计数 思路: 首先考虑含有前导0的情况,可以发现在相同的\(i\)位数中,每个数的出现次数都是相等的.所以我们可以设\(f(i)\)为\(i\)位数每个数的出现次数 ...

  3. 微信小程序~tabBar和navigator一起使用无效

    1.当注册了tabBar的时候,使用navigator时会发现不能跳转,这个时候需要在navigator上加上open-type=’switchTab’ 属性 <navigator open-t ...

  4. P1525 关押罪犯[扩展域并查集]

    题目来源:洛谷 题目描述 S城现有两座监狱,一共关押着N名罪犯,编号分别为1−N.他们之间的关系自然也极不和谐.很多罪犯之间甚至积怨已久,如果客观条件具备则随时可能爆发冲突.我们用“怨气值”(一个正整 ...

  5. 最详细的keepalived+lvs-dr配置文档

    四台台机器: 分发器主:192.168.0.154 分发器备:192.168.0.171 rs_1:192.168.0.131 rs_2:192.168.0.132 keepalived安装: yum ...

  6. 【CLAA系列】CLAA 通讯过程

    名词: MSP:中兴服务器 CS:客户服务器,也就是我们的服务器 GW:网关,这里默认是中兴的网关 Chip:芯片,这里特指包含了Lora标准通讯模块,且针对CLAA做过特殊优化的芯片. Lora:L ...

  7. tensorflow2.0 学习(二)

    线性回归问题 # encoding: utf-8 import numpy as np import matplotlib.pyplot as plt data = [] for i in range ...

  8. DOM内容梳理2

    JavaScript-DOM2(内容整理) 这两天新的知识有点多有点杂一时半会没有整理过来,以后不出意外会一直更行. js节点类型(NODETYPE) 查看节点类型 nodetype属性,返回的结果会 ...

  9. hhhhh我又双叒进步啦!

    虽然说从今天开始短暂的暑假一周假期正式开始,然而第一天我就深感在家有多无聊...所以说还是整天待在学校好丫! 不过,就算在家, 勤奋好学的 我也要认真做题!今天就一鼓作气地把排名刷到了第 50 名!! ...

  10. 2019 SDN第二次上机作业

    2019 SDN第二次上机作业 1. 利用mininet创建如下拓扑,要求拓扑支持OpenFlow 1.3协议,主机名.交换机名以及端口对应正确,请给出拓扑Mininet执行结果,展示端口连接情况 创 ...