leetcode 767 - Reorganize String

https://leetcode.com/problems/reorganize-string/

Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.

Example 1:

Input: S = “aab”
Output: “aba”
Example 2:

Input: S = “aaab”
Output: “”
Note:

S will consist of lowercase letters and have length in range [1, 500].

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
class Solution {
public:
struct Entry {
char c;
int total;

Entry(char _c, int _total) {
c = _c;
total = _total;
}
};

string reorganizeString(string S) {
unordered_map<char, int> maps;

for (char c : S) {
maps[c]++;
}

auto mycomp = [](const Entry &e1, const Entry &e2) {
return e1.total < e2.total;
};
typedef priority_queue<Entry, vector<Entry>, decltype(mycomp)> pq_t;
pq_t pq(mycomp);

for (auto m : maps) {
pq.push(Entry(m.first, m.second));
}

string result;

while (!pq.empty()) {
Entry e = pq.top(); pq.pop();
if (result.empty() || result.back() != e.c) {
result.push_back(e.c);
if (--e.total)
pq.push(e);
} else {
if (pq.empty())
return "";
Entry e2 = pq.top(); pq.pop();
result.push_back(e2.c);
if (--e2.total)
pq.push(e2);
pq.push(e);
}
}

return result;
}
};