[LeetCode] Rearrange String k Distance Apart 按距離為k隔離重排字串
阿新 • • 發佈:2018-12-27
Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string ""
.
Example 1:
str = "aabbcc", k = 3 Result: "abcabc" The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 Answer: "" It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2 Answer: "abacabcd" Another possible answer is: "abcabcda" The same letters are at least distance 2 from each other.
Credits:
Special thanks to @elmirap
這道題給了我們一個字串str,和一個整數k,讓我們對字串str重新排序,使得其中相同的字元之間的距離不小於k,這道題的難度標為Hard,看來不是省油的燈。的確,這道題的解法用到了雜湊表,堆,和貪婪演算法。這道題我最開始想的演算法沒有通過OJ的大集合超時了,下面的方法是參考網上大神的解法,發現十分的巧妙。我們需要一個雜湊表來建立字元和其出現次數之間的對映,然後需要一個堆來儲存這每一堆對映,按照出現次數來排序。然後如果堆不為空我們就開始迴圈,我們找出k和str長度之間的較小值,然後從0遍歷到這個較小值,對於每個遍歷到的值,如果此時堆為空了,說明此位置沒法填入字元了,返回空字串,否則我們從堆頂取出一對對映,然後把字母加入結果res中,此時對映的個數減1,如果減1後的個數仍大於0,則我們將此對映加入臨時集合v中,同時str的個數len減1,遍歷完一次,我們把臨時集合中的對映對由加入堆中,參見程式碼如下:
class Solution { public: string rearrangeString(string str, int k) { if (k == 0) return str; string res; int len = (int)str.size(); unordered_map<char, int> m; priority_queue<pair<int, char>> q; for (auto a : str) ++m[a]; for (auto it = m.begin(); it != m.end(); ++it) { q.push({it->second, it->first}); } while (!q.empty()) { vector<pair<int, int>> v; int cnt = min(k, len); for (int i = 0; i < cnt; ++i) { if (q.empty()) return ""; auto t = q.top(); q.pop(); res.push_back(t.second); if (--t.first > 0) v.push_back(t); --len; } for (auto a : v) q.push(a); } return res; } };
類似題目:
參考資料: