2785: Sort-Vowels-in-a-String
Medium
table of contents
The solution is quite easy to flesh out. First, we need a function to decipher whether a character is a vowel or not.
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
Then, we want to keep track of the indices of all
the vowels inside the string s
so we define
vowelIndices
so that we know where to place them after
sorting the vowels.
<int> vowelIndices; vector
Now, since we know the sorted vowels will
always be sorted in the same order
(AEIOUaeiou
), we can simply record the
frequency of each vowel…
for (int i = 0; i < s.size(); ++i) {
if (isVowel(s[i])) {
++mp[s[i]];
.push_back(i);
vowelIndices}
}
…and then place them in their newly appointed index.
= "AEIOUaeiou";
string vowelOrder int index = 0;
for (int i = 0; i < vowelIndices.size(); ++i) {
while (mp[vowelOrder[index]] == 0) {
++index;
}
[vowelIndices[i]] = vowelOrder[index];
s--mp[vowelOrder[index]];
}
Now, we can simply return the newly sorted s
.
return s;
code
class Solution {
public:
(string s) {
string sortVowels<char, int> mp;
unordered_map<int> vowelIndices;
vectorfor (int i = 0; i < s.size(); ++i) {
if (isVowel(s[i])) {
++mp[s[i]];
.push_back(i);
vowelIndices}
}
= "AEIOUaeiou";
string vowelOrder int index = 0;
for (int i = 0; i < vowelIndices.size(); ++i) {
while (mp[vowelOrder[index]] == 0) {
++index;
}
[vowelIndices[i]] = vowelOrder[index];
s--mp[vowelOrder[index]];
}
return s;
}
private:
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}
};