-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReorganize String.java
37 lines (31 loc) · 1.05 KB
/
Reorganize String.java
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
public class Solution {
public String reorganizeString(String s) {
Map<Character, Integer> count = new HashMap<>();
int maxFreq = 0;
for (final char c : s.toCharArray())
maxFreq = Math.max(maxFreq, count.merge(c, 1, Integer::sum));
if (maxFreq > (s.length() + 1) / 2)
return "";
StringBuilder sb = new StringBuilder();
// (freq, c)
Queue<Pair<Integer, Character>> maxHeap =
new PriorityQueue<>((a, b) -> b.getKey() - a.getKey());
int prevFreq = 0;
char prevChar = '@';
for (final char c : count.keySet())
maxHeap.offer(new Pair<>(count.get(c), c));
while (!maxHeap.isEmpty()) {
// Get the most freq letter.
final int freq = maxHeap.peek().getKey();
final char c = maxHeap.poll().getValue();
sb.append(c);
// Add the previous letter back so that any two adjacent characters are
// not the same.
if (prevFreq > 0)
maxHeap.offer(new Pair<>(prevFreq, prevChar));
prevFreq = freq - 1;
prevChar = c;
}
return sb.toString();
}
}