-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0767.cpp
More file actions
33 lines (30 loc) · 887 Bytes
/
Copy path0767.cpp
File metadata and controls
33 lines (30 loc) · 887 Bytes
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
class Solution {
typedef pair<int, char> pic;
public:
string reorganizeString(const string &s) {
priority_queue<pic> pq;
int count[27] = {0};
string res;
for (char c : s)
count[c & 0x1F]++;
for (int i = 1; i <= 26; i++)
if (count[i] > 0) pq.push({count[i], 'a' + i - 1});
while (!pq.empty()) {
const auto [cnt, c] = pq.top();
pq.pop();
if (pq.empty()) {
if (cnt == 1)
return res + c;
else
return "";
} else {
const auto [ocnt, oc] = pq.top();
pq.pop();
res += c, res += oc;
if (cnt - 1) pq.push({cnt - 1, c});
if (ocnt - 1) pq.push({ocnt - 1, oc});
}
}
return res;
}
};