[LeetCode] 358. Rearrange String k Distance Apart 按距離為k隔離重排字符串


 

Given a non-empty string s 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:

Input: s = "aabbcc", k = 3 Output: "abcabc" Explanation: The same letters are at least distance 3 from each other. 

Example 2:

Input: s = "aaabc", k = 3 Output: "" Explanation: It is not possible to rearrange the string. 

Example 3:

Input: s = "aaadbbcc", k = 2 Output: "abacabcd" Explanation: The same letters are at least distance 2 from each other.

Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.

 

這道題給了我們一個字符串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;
    }
};

 

類似題目:

Task Scheduler

 

參考資料:

https://leetcode.com/problems/rearrange-string-k-distance-apart/

https://leetcode.com/discuss/108174/c-unordered_map-priority_queue-solution-using-cache

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM