-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_358.java
More file actions
47 lines (42 loc) · 1.26 KB
/
Copy pathP_358.java
File metadata and controls
47 lines (42 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package leetcode.hard;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.PriorityQueue;
public class P_358 {
static class Pair {
char c;
int count;
Pair(char c, int count) {
this.c = c;
this.count = count;
}
}
public String rearrangeString(String s, int k) {
final PriorityQueue<Pair> pq = new PriorityQueue<>((a, b) -> Integer.compare(b.count, a.count));
final Deque<Pair> q = new ArrayDeque<>();
final int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
for (char c = 'a'; c <= 'z'; c++) {
if (count[c - 'a'] > 0) {
pq.offer(new Pair(c, count[c - 'a']));
}
}
final StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
final Pair curr = pq.remove();
sb.append(curr.c);
curr.count -= 1;
q.offerLast(curr);
if (q.size() < k) {
continue;
}
final Pair fromQ = q.removeFirst();
if (fromQ.count > 0) {
pq.offer(fromQ);
}
}
return sb.length() == s.length() ? sb.toString() : "";
}
}