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/
這題就是貪心算法。對(duì)于字符串處理來(lái)講,如果不care最終的符號(hào)序,就要以考慮用統(tǒng)計(jì)重排的方法。
1. 統(tǒng)計(jì)所有字符的出現(xiàn)頻率;
2. 按出現(xiàn)頻率從高到低優(yōu)先填好所有字符;
如果全部都是ASCII碼,共出現(xiàn)m個(gè)不同字符,第2步,可以:
1. 用最大堆來(lái)做,也可以直接排序,時(shí)間復(fù)雜度都是O(n+mlgm),空間復(fù)雜度就是O(m)。因?yàn)閙<256<<n,所以最終復(fù)雜度也可以說(shuō)是O(n)。
2. 也可以直接用一個(gè)vector<list<char> >記錄每個(gè)頻率下的字符來(lái)做。用vector<list<char> >就是O(2n)的時(shí)間復(fù)雜度了。空間復(fù)雜度高點(diǎn),O(n)。
?
Rearrange a string so that all same characters become d distance away
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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