[Leetcode]358. Rearrange String k Distance Apart (貪心,窗口,堆,字符)

 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.


題解:貪心。統計每個字符個數,每次優先放字符個數多的。


class Solution {
public:
    string rearrangeString(string str, int k) {   //1604MS
        if(k<=1) return str;
        string res="";
        int len=str.size();
        unordered_set<char> Set;
        map<char,int> Map;
        for(char c:str) {
            Map[c]++;
        }
        bool f=true;
        int ans=0;
        while(true) {
            char nex;
            int t=-1;
            f=false;
            for(int i=0;i<26;i++) {
                char tmp='a'+i;
                if(Map[tmp]<=0) continue;
                if(Set.empty()||Set.find(tmp)==Set.end()) {
                    f=true;
                    if(Map[tmp]>t) {
                        t=Map[tmp];
                        nex=tmp;
                    }
                }
            }
            if(!f) break;
            res+=nex;
            ans++;
            Map[nex]--;
            if(ans==len) {
                f=true;break;
            }
            if(ans>=k) {
                Set.erase(res[ans-k]);
            }
            Set.insert(nex);
        }
        if(!f) return "";
        else return res;
    }
};

class Solution {
public:
    string rearrangeString(string str, int k) {   //128MS
        if(k == 0) return str;
        int length = (int)str.size(); 
        
        string res;
        unordered_map<char, int> dict;
        priority_queue<pair<int, char>> pq;
        
        for(char ch : str) dict[ch]++;
        for(auto it = dict.begin(); it != dict.end(); it++){
            pq.push(make_pair(it->second, it->first));
        }
        
        while(!pq.empty()){
            vector<pair<int, char>> cache; //store used char during one while loop
            int count = min(k, length); //count: how many steps in a while loop
            for(int i = 0; i < count; i++){
                if(pq.empty()) return "";
                auto tmp = pq.top();
                pq.pop();
                res.push_back(tmp.second);
                if(--tmp.first > 0) cache.push_back(tmp);
                length--;
            }
            for(auto p : cache) pq.push(p);
        }
        return res;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章