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; } };
时间: 2024-11-05 06:27:38