Given a string and a positive integer d. some characters may be repeated in the given string. rearrange characters of the given string such that the same characters become d distance away from each other. note that there can be either possible rearrangements, the output shocould be one of the possible rearrangements. if no such arrangement is possible, that shoshould also be reported.
Expected time complexity is O (n) where n is length of input string.
Examples:
Input: "abb", d = 2
Output: "bab"
Input: "aacbbc", d = 3
Output: "abcabc"
Input: "geeksforgeeks", d = 3
Output: egkegkesfesor
Input: "aaa", d = 2
Output: Cannot be rearranged
From: http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/
This is the greedy algorithm. For string processing, if you do not care about the final signed order, you need to consider the method of statistical shuffling.
1. Count the occurrence frequency of all characters;
2. Fill in all characters first from high to low according to the frequency of occurrence;
If all the characters are ASCII codes, a total of m different characters are displayed. In step 1, you can:
1. The largest heap can be used for direct sorting. The time complexity is O (n + mlgm), and the space complexity is O (m ). Because m <256 <n, the final complexity is O (n ).
2. You can also use a vector <list <char> to record the characters at each frequency. Using vector <list <char> is the time complexity of O (2n. High space complexity, O (n ).
Rearrange a string so that all same characters become d distance away