[LeetCode] Reverse Words With Same Vowel Count

3775. Reverse Words With Same Vowel Count

You are given a string s consisting of lowercase English words, each separated by a single space.

Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged.

Return the resulting string.

Vowels are 'a', 'e', 'i', 'o', and 'u'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

class Solution {
unordered_set<char> vowel{'a','e','i','o','u'};
int countVowels(string& s) {
int res = 0;
for(auto& ch : s) {
if(vowel.count(ch)) res++;
}
return res;
}
public:
string reverseWords(string s) {
assert(s[0] != ' ');
string res = "", chunk = "";
s.push_back(' ');
int vowels = -1;
for(auto& ch : s) {
if(ch == ' ') {
if(vowels == -1) {
vowels = countVowels(chunk);
} else {
if(countVowels(chunk) == vowels) {
reverse(begin(chunk), end(chunk));
}
}
res += chunk;
chunk = "";
res.push_back(' ');
} else {
chunk.push_back(ch);
}
}


res.pop_back();
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/reverse-words-with-same-vowel-count/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.