leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0767.cpp (887B)
0 class Solution {
1 typedef pair<int, char> pic;
3 public:
4 string reorganizeString(const string &s) {
5 priority_queue<pic> pq;
6 int count[27] = {0};
7 string res;
9 for (char c : s)
10 count[c & 0x1F]++;
11 for (int i = 1; i <= 26; i++)
12 if (count[i] > 0) pq.push({count[i], 'a' + i - 1});
14 while (!pq.empty()) {
15 const auto [cnt, c] = pq.top();
16 pq.pop();
17 if (pq.empty()) {
18 if (cnt == 1)
19 return res + c;
20 else
21 return "";
22 } else {
23 const auto [ocnt, oc] = pq.top();
24 pq.pop();
25 res += c, res += oc;
26 if (cnt - 1) pq.push({cnt - 1, c});
27 if (ocnt - 1) pq.push({ocnt - 1, oc});
28 }
29 }
30 return res;
31 }
32 };