日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

Rearrange a string so that all same characte

系統 2267 0

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元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 固始县| 阿拉善盟| 东兰县| 闸北区| 河源市| 全南县| 桂东县| 临汾市| 黄梅县| 周口市| 水城县| 聂荣县| 道孚县| 云霄县| 依兰县| 大悟县| 绥阳县| 柳河县| 金昌市| 鞍山市| 七台河市| 西盟| 永新县| 南郑县| 虞城县| 鹤壁市| 铜川市| 武夷山市| 驻马店市| 黎平县| 太原市| 徐汇区| 通城县| 临沂市| 奎屯市| 银川市| 信丰县| 丰县| 乌兰察布市| 库尔勒市| 嵊泗县|