|
| 1 | +package Top_K_Elements; |
| 2 | + |
| 3 | +// Problem Statement: Rearrange String (hard) |
| 4 | +// LeetCode Question: 767. Reorganize String |
| 5 | + |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.PriorityQueue; |
| 9 | + |
| 10 | +public class Problem_11_Rearrange_String { |
| 11 | + public String rearrangeString(String str) { |
| 12 | + Map<Character, Integer> charFrequencyMap = new HashMap<>(); |
| 13 | + for (char chr : str.toCharArray()) |
| 14 | + charFrequencyMap.put(chr, charFrequencyMap.getOrDefault(chr, 0) + 1); |
| 15 | + |
| 16 | + PriorityQueue<Map.Entry<Character, Integer>> maxHeap = |
| 17 | + new PriorityQueue<Map.Entry<Character, Integer>>( |
| 18 | + (e1, e2) -> e2.getValue() - e1.getValue()); |
| 19 | + |
| 20 | + // add all characters to the max heap |
| 21 | + maxHeap.addAll(charFrequencyMap.entrySet()); |
| 22 | + |
| 23 | + Map.Entry<Character, Integer> previousEntry = null; |
| 24 | + StringBuilder resultString = new StringBuilder(str.length()); |
| 25 | + while (!maxHeap.isEmpty()) { |
| 26 | + Map.Entry<Character, Integer> currentEntry = maxHeap.poll(); |
| 27 | + // add the previous entry back in the heap if its frequency is greater than zero |
| 28 | + if (previousEntry != null && previousEntry.getValue() > 0) |
| 29 | + maxHeap.offer(previousEntry); |
| 30 | + // append the current character to the result string and decrement its count |
| 31 | + resultString.append(currentEntry.getKey()); |
| 32 | + currentEntry.setValue(currentEntry.getValue() - 1); |
| 33 | + previousEntry = currentEntry; |
| 34 | + } |
| 35 | + |
| 36 | + // if we were successful in appending all the characters to the result string, |
| 37 | + // return it |
| 38 | + return resultString.length() == str.length() ? resultString.toString() : ""; |
| 39 | + } |
| 40 | +} |
0 commit comments