(FB) Rearrange String k Distance Apart
(高频) Rearrange String k Distance Apart
换句话说,条件允许的时候我们要从堆顶拿元素,但是堆顶元素非法的时候,不一定代表此时无解。
因此我们需要在此基础上加一个 queue,来维护这次循环寻找元素时候的解;如果在任何时刻 maxHeap 里没东西了,但是 queue 里还有,都可以说明此时真的没有合法元素了,返回 "".
速度尚可,超过 48%
public class Solution {
private class Tuple{
char chr;
int count;
int timestamp;
public Tuple(char chr, int count){
this.chr = chr;
this.count = count;
}
}
private class TupleComparator implements Comparator<Tuple>{
public int compare(Tuple a, Tuple b){
if(a.count != b.count) return b.count - a.count;
else return a.timestamp - b.timestamp;
}
}
public String rearrangeString(String str, int k) {
int[] hash = new int[26];
PriorityQueue<Tuple> maxHeap = new PriorityQueue<Tuple>(new TupleComparator());
for(int i = 0; i < str.length(); i++){
hash[str.charAt(i) - 'a']++;
}
for(int i = 0; i < 26; i++){
if(hash[i] > 0) maxHeap.offer(new Tuple((char)(i + 'a'),hash[i]));
}
StringBuilder sb = new StringBuilder();
Queue<Tuple> queue = new LinkedList<>();
int time = 0;
while(!maxHeap.isEmpty()){
Tuple tuple = maxHeap.poll();
time ++;
if(tuple.timestamp != 0 && time - tuple.timestamp < k){
queue.offer(tuple);
continue;
}
sb.append(tuple.chr);
tuple.count --;
tuple.timestamp = time;
if(tuple.count != 0) maxHeap.offer(tuple);
while(!queue.isEmpty()) maxHeap.offer(queue.poll());
}
return !queue.isEmpty() ? "": sb.toString();
}
}注意,下面的代码和画图有 bug.
"aabbccd"
k = 3
返回了 abcacdb, c 冲突了,正解是 abcabcd
改良版的写法建立在下图的逻辑上:
这种写法适合不适合写自己填空格的 follow-up,有待研究。。至少 AAABBBCCCDDD 这种填充时候需要额外判断一下 “这个 space 到底是不是必要的” 这类问题。

12ms,超过 90.16%
(FB) 不改顺序的 cooldown 输出
(FB) 变种:任务调度,生成“最优”的任务序列,可以用空格占位;
Last updated