3913. Sort Vowels by Frequency
You are given a string s consisting of lowercase English characters.
Rearrange only the vowels in the string so that they appear in non-increasing order of their frequency.
If multiple vowels have the same frequency, order them by the position of their first occurrence in s.
Return the modified string.
Vowels are 'a', 'e', 'i', 'o', and 'u'.
The frequency of a letter is the number of times it occurs in the string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: string sortVowels(string s) { unordered_map<char, pair<int,int>> freq; unordered_set<char> v{'a','e','i','o','u'}; for(int i = s.length() - 1; i >= 0; i--) { if(!v.count(s[i])) continue; freq[s[i]] = {freq[s[i]].first + 1, i}; } vector<char> S(begin(v), end(v)); sort(begin(S), end(S), [&](auto& a, auto& b) { if(freq[a].first != freq[b].first) return freq[a].first < freq[b].first; return freq[a].second > freq[b].second; }); for(auto& ch : s) { if(!v.count(ch)) continue; ch = S.back(); if(--freq[S.back()].first == 0) S.pop_back(); } return s; } };
|