zoukankan      html  css  js  c++  java
  • LeetCode "Rearrange String k Distance Apart"

    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;
        }
    };
  • 相关阅读:
    ural1018(树形dp)
    hdu1011(树形dp)
    poj1463(树形dp)
    poj1655(树形dp)
    poj1155(树形dp)
    hdu2196(树形dp)
    hdu1520(树形dp)
    hdu2126(求方案数的01背包)
    运用bootstrap框架的时候 引入文件的问题
    动态的改变标签内的src属性
  • 原文地址:https://www.cnblogs.com/tonix/p/5586115.html
Copyright © 2011-2022 走看看