Rearrange string k distance apart
Introduction
Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".
Example 1: s = “aabbcc”, k = 3 Result: “abcabc”
The same letters are at least distance 3 from each other. Example 2: s = “aaabc”, k = 3 Answer: ""
It is not possible to rearrange the string. Example 3: s = “aaadbbcc”, k = 2 Answer: “abacabcd” Another possible answer is: “abcabcda” The same letters are at least distance 2 from each other.
Solution
First of all, create a Pair class that has three properties: character c, count of the character and a timestamp (timestamp is used in priority queue to maintain descending order). Then create a priority queue based on the count of the character and timestamp when counts are equal to ensure FIFO order. Create a pair for each unique character with its count after traversing the whole string and add all pairs to priority queue, then pop out k pairs with each minus one if the queue is not empty. If the count is not zero, add it to a temporary list and put it back to queue at the end. At the same time add current character to string builder. For cases that do not have an answer, this line of code if(pair.count >= 1 && queue.size() + temp.size() < k) return ""; will check if current character will appear sometime later but there are not enough characters to set them k distance apart.
1 | public class RearrangeStringKDistanceApart { |