-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
65 lines (51 loc) · 1.55 KB
/
main.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public:
string rearrangeString(string s, int k) {
unordered_map<char, int> char_count;
for (char c : s) ++char_count[c];
priority_queue<pair<int, char>, vector<pair<int, char>>> pq;
for (auto [c, cnt] : char_count) pq.push({cnt, c});
string result;
deque<pair<int, char>> q;
while (!pq.empty()) {
auto [cnt, c] = pq.top();
pq.pop();
result.push_back(c);
q.push_back({cnt - 1, c});
if (q.size() >= k) {
if (q.front().first > 0) pq.push(q.front());
q.pop_front();
}
}
return result.size() == s.size() ? result : "";
}
};
class Solution {
public:
string rearrangeString(string s, int k) {
array<int, 26> charFreq;
charFreq.fill(0);
for (char c : s) ++charFreq[c - 'a'];
priority_queue<array<int, 2>> pq;
for (int i = 0; i < 26; ++i) {
if (int f = charFreq[i]; f > 0) {
pq.push({f, i});
}
}
string result;
queue<array<int, 3>> q;
for (int i = 0; i < s.size(); ++i) {
if (!q.empty() && i - k >= q.front()[0]) {
auto [_, f, c] = q.front();
q.pop();
pq.push({f, c});
}
if (pq.empty()) return "";
auto [f, c] = pq.top();
pq.pop();
result += 'a' + c;
if (--f > 0) q.push({i, f, c});
}
return result;
}
};