Coding problem · Easy · Basics
Count the Vowels
Easy Algorithms & data structures
Return the number of vowels in s. Vowels are a, e, i, o and u, in upper or lower case.
Example 1
Input: s = "Hello World" Output: 3
Example 2
Input: s = "sky" Output: 0
Hints
Hint 1
Loop over the characters and check whether each one is in the set of vowels.
Hint 2
Lower-case the character (or the whole string) first so 'A' and 'a' both count.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Lower-case each character and count it if it's one of the five vowels. A set (or a string of vowels) makes the membership check simple.
Reference solution
function countVowels(s) {
let count = 0;
for (const ch of s.toLowerCase()) if ('aeiou'.includes(ch)) count++;
return count;
}
function countVowels(s: string): number {
let count = 0;
for (const ch of s.toLowerCase()) if ('aeiou'.includes(ch)) count++;
return count;
}
def count_vowels(s: str) -> int:
return sum(1 for ch in s.lower() if ch in 'aeiou')
<?php
function countVowels(string $s): int
{
return preg_match_all('/[aeiou]/i', $s);
}
class Solution {
public int countVowels(String s) {
int count = 0;
for (char ch : s.toLowerCase().toCharArray()) if ("aeiou".indexOf(ch) >= 0) count++;
return count;
}
}
More Basics problems
- Reverse a String · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy
- Make an Acronym · Easy