首页 > 代码库 > Rearrange a string so that all same characters become d distance away

Rearrange a string so that all same characters become d distance away

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 many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should 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
摘自:http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

这题就是贪心算法。对于字符串处理来讲,如果不care最终的符号序,就要以考虑用统计重排的方法。

1. 统计所有字符的出现频率;

2. 按出现频率从高到低优先填好所有字符;

如果全部都是ASCII码,共出现m个不同字符,第2步,可以:

1. 用最大堆来做,也可以直接排序,时间复杂度都是O(n+mlgm),空间复杂度就是O(m)。因为m<256<<n,所以最终复杂度也可以说是O(n)。

2. 也可以直接用一个vector<list<char> >记录每个频率下的字符来做。用vector<list<char> >就是O(2n)的时间复杂度了。空间复杂度高点,O(n)。

 

Rearrange a string so that all same characters become d distance away