If possible, output any possible result. If not possible, return the empty string.
Input: S = "aab"
Output: "aba"
Input: S = "aaab"
Output: ""
// Hashmap + greedy + heap
string reorganizeString(string S) { // time: O(nlogn); space: O(n)
int len = S.length();
vector<int> count(26, 0);
for (char ch : S) {
if (count[ch - 'a'] > (len + 1) / 2) return "";
++count[ch - 'a'];
}
priority_queue<pair<int, char> > pq;
for (int i = 0; i < 26; ++i) {
if (!count[i]) continue;
pq.push({count[i], (char)('a' + i)});
}
string res;
while (!pq.empty()) {
auto t = pq.top(); pq.pop();
if (res.empty() || t.second != res[res.length() - 1]) {
res += t.second;
if (--t.first > 0) pq.push(t);
}
else if (!pq.empty()) {
auto u = pq.top(); pq.pop();
res += u.second;
if (--u.first > 0) pq.push(u);
pq.push(t);
} else {
return "";
}
}
return res;
}
// Hashmap + greedy + heap
string reorganizeString(string S) { // time: O(nlogn); space: O(n)
vector<int> count(26, 0);
for (char ch : S) {
if (++count[ch - 'a'] > (S.length() + 1) / 2) return "";
}
priority_queue<pair<int, char> > pq;
for (int i = 0; i < 26; ++i) {
if (!count[i]) continue;
pq.push({count[i], (char)('a' + i)});
}
string res;
while (pq.size() >= 2) {
auto t = pq.top(); pq.pop();
auto u = pq.top(); pq.pop();
res.push_back(t.second);
res.push_back(u.second);
if (--t.first > 0) pq.push(t);
if (--u.first > 0) pq.push(u);
}
if (!pq.empty()) res.push_back(pq.top().second);
return res;
}