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
class Solution {
public:
string reorganizeString(string S) {
auto mycomp = [](const pair<char,int> &p1, const pair<char,int> &p2) {
return p1.second < p2.second;
};

typedef priority_queue<pair<char,int>, vector<pair<char,int>>, decltype(mycomp)> pq_t;
pq_t pq(mycomp);

vector<int> count(26, 0);

for (char c : S)
count[c-'a']++;

for (int i = 0; i < 26; i++) {
if (count[i] != 0)
pq.push({i+'a', count[i]});
}

string result;
pair<char, int> wait = {0, -1};

while (!pq.empty()) {
auto p = pq.top(); pq.pop();
if (!result.empty() && result.back() == p.first)
return "";

result.push_back(p.first);

if (wait.second != -1) {
pq.push(wait);
wait = {0, -1};
}

if (--p.second > 0)
wait = {p.first, p.second};
}

return wait.second != -1 ? "" : result;
}
};