/*
* @lc app=leetcode id=767 lang=cpp
*
* [767] Reorganize String
*/
// @lc code=start
class Solution {
public:
string reorganizeString(string S) {
vector<int> freq(26, 0);
for (const auto c : S) {
++freq[c - 'a'];
}
string res;
for (int i = 0, last = -1; i < S.length(); ++i) {
int mx = 0, mx_cnt = 0;
bool found = false;
for (int j = 0; j < 26; ++j) {
if (freq[j] > mx_cnt && j != last) {
mx = j;
mx_cnt = freq[j];
found = true;
}
}
if (!found) return "";
res += (mx + 'a');
--freq[mx];
last = mx;
}
return res;
}
};
// @lc code=end