-
Notifications
You must be signed in to change notification settings - Fork 3
/
358.cpp
34 lines (33 loc) · 908 Bytes
/
358.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
string rearrangeString(string s, int k) {
if (k == 0) return s;
unordered_map<char, int> mp;
priority_queue<pair<int, char>> pq;
for (auto c : s) {
mp[c]++;
}
for (auto& [c, cnt] : mp) {
pq.push(make_pair(cnt, c));
}
string res = "";
int n = s.size();
while (!pq.empty()) {
int size = min(n, k);
vector<pair<int, char>> v;
while (size) {
if (pq.empty()) return "";
auto [cnt, c] = pq.top();
pq.pop();
res.push_back(c);
if (cnt - 1 > 0) {
v.push_back(make_pair(cnt - 1, c));
}
size--;
n--;
}
for (auto p : v) pq.push(p);
}
return res;
}
};