码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Rearrange String k Distance Apart"

时间:2016-06-15 08:01:01      阅读:249      评论:0      收藏:0      [点我收藏+]

标签:

Greedy using priority_queue and hashmap. The basic idea is to have k buckets - and we fill it greedily.

And I agree that the code below can be cleaner:

struct Rec
{
    Rec(char _c, int _cnt) :c(_c), cnt(_cnt) {}
    char c;
    int cnt;    
};

struct Cmp
{
    bool operator()(const Rec &r1, const Rec &r2) 
    {
        return r1.cnt < r2.cnt;
    }
};
class Solution {
public:
    string rearrangeString(string str, int k) 
    {
        if (k < 2)return str;
        int n = str.length();
        
        //    cnt
        int maxcnt = 0;
        vector<int> cnt(26);
        for (auto c : str)
        {
            cnt[c - a] ++;
            maxcnt = max(maxcnt, cnt[c - a]);
        }
        //    Check validity
        int max_need = (maxcnt - 1) * k + 1;
        if (max_need > n) return "";

        //    Queue
        priority_queue<Rec, vector<Rec>, Cmp> q;
        for (int i = 0; i < 26; i++)
        {
            if (cnt[i] > 0)
            {
                q.push(Rec(i + a, cnt[i]));
            }
        }

        //
        vector<string> secs(maxcnt);
        int j = 0;
        while (!q.empty())
        {
            Rec r = q.top(); q.pop();
            for (int i = 0; i < r.cnt; i++)
            {
                secs[j] += r.c;
                j = (j + 1) % maxcnt;
            }
        }

        string ret;        
        for (int i = 0; i < secs.size(); i++)
        {
            if (i < secs.size() - 1 && secs[i].length() < k) return "";
            ret += secs[i];
        }

        return ret;
    }
};

LeetCode "Rearrange String k Distance Apart"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5586115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!