-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathProblem_11_Rearrange_String.java
40 lines (33 loc) · 1.65 KB
/
Problem_11_Rearrange_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
38
39
40
package Top_K_Elements;
// Problem Statement: Rearrange String (hard)
// LeetCode Question: 767. Reorganize String
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
public class Problem_11_Rearrange_String {
public String rearrangeString(String str) {
Map<Character, Integer> charFrequencyMap = new HashMap<>();
for (char chr : str.toCharArray())
charFrequencyMap.put(chr, charFrequencyMap.getOrDefault(chr, 0) + 1);
PriorityQueue<Map.Entry<Character, Integer>> maxHeap =
new PriorityQueue<Map.Entry<Character, Integer>>(
(e1, e2) -> e2.getValue() - e1.getValue());
// add all characters to the max heap
maxHeap.addAll(charFrequencyMap.entrySet());
Map.Entry<Character, Integer> previousEntry = null;
StringBuilder resultString = new StringBuilder(str.length());
while (!maxHeap.isEmpty()) {
Map.Entry<Character, Integer> currentEntry = maxHeap.poll();
// add the previous entry back in the heap if its frequency is greater than zero
if (previousEntry != null && previousEntry.getValue() > 0)
maxHeap.offer(previousEntry);
// append the current character to the result string and decrement its count
resultString.append(currentEntry.getKey());
currentEntry.setValue(currentEntry.getValue() - 1);
previousEntry = currentEntry;
}
// if we were successful in appending all the characters to the result string,
// return it
return resultString.length() == str.length() ? resultString.toString() : "";
}
}