358. Rearrange String k Distance Apart【discuss】

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

https://leetcode.com/discuss/108174/c-unordered_map-priority_queue-solution-using-cache
Discuss的代码,写的很完美啊:
用一个cache去存储需要间隔k的char。在下一次的for循环里再放入res。

class Solution {
public:
    string rearrangeString(string str, int k) {
        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;
    }
};    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,663评论 2 45
  • 问答 一、dom对象的innerText和innerHTML有什么区别? innerTextinnerText是一...
    婷楼沐熙阅读 3,097评论 0 0
  • 他是一个完美的好人 从来不会因糟糕的事情发脾气 也不会摔门而去 从来不会 他是一个完美的好人 从来不会因不公正的遭...
    孟不言阅读 1,001评论 0 3