Wednesday, August 23rd
Reorganize a string
Given a string, rearrange the characters so that no 2 adjacent characters are the same
The idea is to use a priority queue to repeatedly use the characters of higher frequencies. To ensure no 2 adjacent characters are the same, we remove a character from both of the top 2 elements in a priority queue
To populate the priority queue based on character occurrences, we first calculate character frequencies
Then we populate the priority queue with pairs, where the first element is the frequency of a character, and the second element of the pair is the character itself. With this organization, we can easily use the priority queue's sorting mechanism
Initiate the solution string
Now we repeatedly pull characters from the top of the queue, and append the characters to our solution string.
As long as there are 2 or more characters remaining in the queue, we retrieve and then pop the top 2 elements in the priority queue. We then append each character to the solution string. Then, if there are 1 or more characters remaining in the character's count, we push the character back onto the priority_queue, decrementing its frequency by 1
Lastly, if a character pair remains in the queue (remember the above while loop operates when there are 2 or more character pairs on the priority queue), then we test the frequency for the character. If the character pair has a remaining frequency of more than 2, then we return an empty string because we can't properly organize the string.
Otherwise, if there is a character frequency of 1, we append it to the solution string
Finally, return the solution string
Kind of tricky converting between integers and characters
Shout out to CHIIKUU for a nice implementation using double tops of the priority queue
Comments
Post a Comment