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
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
