[LeetCode] Sort Vowels in a String

2785. Sort Vowels in a String

Given a 0-indexed string s, permute s to get a new string t such that:

  • All consonants remain in their original places. More formally, if there is an index i with 0 <= i < s.length such that s[i] is a consonant, then t[i] = s[i].
  • The vowels must be sorted in the nondecreasing order of their ASCII values. More formally, for pairs of indices i, j with 0 <= i < j < s.length such that s[i] and s[j] are vowels, then t[i] must not have a higher ASCII value than t[j].

Return the resulting string.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string sortVowels(string s) {
vector<int> cap;
vector<char> v;
unordered_set<char> us{'a','e','i','o','u'};
for(int i = 0; i < s.length(); i++) {
char ch = ::tolower(s[i]);
if(us.count(ch)) {
v.push_back(s[i]);
cap.push_back(i);
}
}
sort(begin(v), end(v));
for(int i = 0; i < v.size(); i++) {
s[cap[i]] = v[i];
}
return s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/22/PS/LeetCode/sort-vowels-in-a-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.