767. Reorganize String
Input: S = "aab"
Output: "aba"Input: S = "aaab"
Output: ""class Solution {
public:
string reorganizeString(string S) {
// sort the string by occurance and reorder them as count * val;
// having two pointers i,j: starting from 0, and (n-1)1/2 + 1, append the result sequentially from i and j
int n = S.size();
vector<int> m (26);
for(char c : S)m[c-'a']++;
vector<pair<int, char>> charCounts;
for(int i = 0 ; i < 26; i++){
if (m[i] > (n + 1)/2) return "";
if(m[i]) charCounts.push_back({m[i], i+'a'});
}
sort(charCounts.rbegin(), charCounts.rend());
string sorted;
for(auto& p :charCounts)
sorted += string(p.first, p.second);
string ans;
for(int i = 0, j = (n-1)/2 + 1; i <= (n-1)/2; i++, j++){
ans += sorted[i];
if(j < n) ans += sorted[j];
}
return ans;
}
};Last updated
Was this helpful?