Problem overview
The function countVowels receives a string s and returns how many vowels it has. The vowels are a, e, i, o and u, in lower or upper case. The letter y is not a vowel here, and every other character (consonants, spaces, digits, punctuation) is skipped.
For "Hello World" the answer is 3: the vowels are e, o and o. For "AlgoCademy" it is 4: A, o, a and e, because the upper-case A counts and the y doesn't. For "Why try?" it is 0.
Approach
The function looks at each character once and asks one question: is it one of the ten vowel characters? To keep that question short, it stores the ten vowels in a string, "aeiouAEIOU", and asks whether the character occurs in it. Storing both cases means the function doesn't have to convert anything to lower case first.
The question is answered with find. vowels.find(c) searches the string vowels for the character c and returns its position, or the special constant string::npos when it isn't there. So c is a vowel exactly when the result is not string::npos.
Here is the loop on "Hello World", one character at a time:
'H' skip count=0
'e' vowel count=1
'l' skip count=1
'l' skip count=1
'o' vowel count=2
' ' skip count=2
'W' skip count=2
'o' vowel count=3
'r' skip count=3
'l' skip count=3
'd' skip count=3
The space is checked like any other character and is simply not found in vowels.
Step by step
- Store the vowels. Create a
stringnamedvowelsholding"aeiouAEIOU". The letter y is left out on purpose. - Create
countas anintstarting at 0. No character has been checked yet. - Visit every character. A range-based
forloop with acharvariablecoversworks, because a string is a sequence of chars. - Test and count. Inside the loop, if
vowels.find(c) != string::npos, add 1 tocountwith++. Characters that aren't invowelsdo nothing. - Return
countafter the loop, not inside it, so that every character is checked first.
The solution in C++
class Solution {
public:
int countVowels(string s) {
string vowels = "aeiouAEIOU";
int count = 0;
for (char c : s) {
if (vowels.find(c) != string::npos) {
count++;
}
}
return count;
}
};
The C++ details:
- Range-based
for.for (char c : s)givesca copy of each character in turn, from the first to the last. There is no index to manage and no risk of going out of bounds. string::findhas several overloads. It accepts a string or a singlechar. With acharit returns the position of its first occurrence as asize_t, an unsigned type, orstring::npos, which is the largest value of that type. That is why the comparison usesnposby name and not a number such as -1 or 0: position 0 is a valid result, the firstainvowels.- The return value of
findis not a boolean. Writingif (vowels.find(c))would be false only fora, which is at position 0, and true for every other character, including those that were not found. - The string is copied. The parameter is passed by value. For long strings, a
const string¶meter avoids the copy, but the lesson keeps the signature simple.
Why a string of vowels
The test could also be written as ten comparisons joined with ||: c == 'a' || c == 'e' || .... That is long and easy to get wrong, for example by forgetting one upper-case letter. A string of vowels keeps the list of vowels in one place, and the loop body stays one line long whatever the list contains. Changing which letters count is then a change to one string, not to the logic.
An alternative: convert to lower case
Another way is to store only "aeiou" and lower-case each character with tolower before searching. That is shorter to store, but each character needs a conversion, and tolower takes and returns an int, so the result needs a cast back to char for find to pick the single-character overload. On "AlgoCademy" this version also counts 4. Keeping both cases in one string avoids the conversion and the cast.
Complexity
Time: O(n) for a string of n characters. Each character costs one search of a ten-character string, which is a constant amount of work. Space: O(1) beyond the copy of the input.
Edge cases and common mistakes
- Upper case.
"AEIOUaeiou"returns 10. If only the lower-case vowels were stored, the upper-case ones would be missed. - The letter y.
"Why try?"returns 0, and so does"xyz". - Non-letters. Spaces, digits and punctuation are never in
vowels, so they are skipped without special handling. - Returning inside the loop. A
return count;inside the loop body would end the function after the first character. - Repeated vowels. Every occurrence counts, even when two vowels are side by side or the same letter repeats, so
"AEIOUaeiou"returns 10 and not 5.
Testing
s = "Hello World"gives 3.s = "AlgoCademy"gives 4.s = "Why try?"gives 0.s = "AEIOUaeiou"gives 10.s = "xyz"gives 0.
