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, such as consonants, spaces, digits and punctuation, is skipped.
In "Hello World" the vowels are e, o and o, so the answer is 3. In "AlgoCademy" they are A, o, a and e, which makes 4: the capital A counts and the y doesn't. In "Why try?" there are none, so the answer is 0.
Approach
Look at each character once and keep a count. For each character, ask one question: is it one of the ten vowel characters? A string holding all ten, "aeiouAEIOU", answers that question with its contains method. Putting both cases in the string means you don't need to convert anything to lower case.
Step by step
- Store the vowels in
let vowels = "aeiouAEIOU". It is aletbecause it never changes. The letter y is not in it. - Create
var count = 0for the vowels found so far. It is avarbecause it grows inside the loop. - Loop over
swithfor c in s. Looping over aStringgives its elements one at a time, and each is aCharacter. - Test each character.
vowels.contains(c)istruewhencappears invowels. If it does, add 1 tocountwith+= 1, since Swift has no++. - Return
countafter the loop, so every character is checked first.
The solution in Swift
class Solution {
func countVowels(_ s: String) -> Int {
let vowels = "aeiouAEIOU"
var count = 0
for c in s {
if vowels.contains(c) {
count += 1
}
}
return count
}
}
Swift details worth knowing:
- Strings hold characters. A
Stringis a collection ofCharactervalues, and that is whyfor c in sworks and whyvowels.contains(c)accepts aCharacter. You can't get a character withs[0]: Swift strings aren't indexed by integers. Loop over them, or useArray(s)when you need positions. countas a name. Strings and arrays also have a property namedcount. Herecountis a local variable, so there is no clash, buts.countwould be the number of characters ins.- Exact comparison.
containscompares characters exactly, so"A"and"a"are different characters. That is why both cases are invowels. - Single quotes don't exist. A one-character literal is written with double quotes, like
"a", and Swift decides from the context whether it is aStringor aCharacter.
Edge cases and common mistakes
- No vowels.
"Why try?"and"rhythm"both give 0. - Upper case.
"AEIOU"gives 5. A vowel string with only lower-case letters would miss them. - Digits and punctuation.
"a1e2"gives 2, because the digits aren't invowels. - Repeated vowels.
"queue"gives 4: u, e, u and e each count, because the loop visits characters, not distinct letters. - Returning inside the loop. The function would stop after the first character.
- Treating y as a vowel. The lesson says it isn't.
Testing
"Hello World"gives 3."AlgoCademy"gives 4."Why try?"gives 0."queue"gives 4."AEIOU"gives 5."a1e2"gives 2.
