This problem is like a tiny letter hunt. You are given a word or sentence, and your job is to count how many vowels appear inside it. The vowels are a, e, i, o, and u.
You do not need to change the text or rearrange anything. You simply look at each character and count the ones that are vowels. If a letter is not a vowel, you ignore it and move on. Uppercase letters can count too if the problem says so, so it is smart to be careful with both big and small letters.
For example, "apple" has 2 vowels because it contains a and e. The word "sky" has 0 vowels because none of its letters belong to the vowel group. A longer word like "education" has even more, so careful counting matters.
The answer is always just one number: how many vowels you found. If the text is empty, the answer is 0. If the same vowel appears many times, each one counts, so you have to scan the whole text from start to finish.
Example Input & Output
Example 1: "apple" contains 2 vowels (a, e)
Example 2: "sky" contains no vowels
Example 3: "education" contains 5 vowels (e, u, a, i, o)
Algorithm Flow
Solution Approach
This problem asks us to count the vowels in a given string. The vowels are a, e, i, o, and u, and we need to include both uppercase and lowercase versions. Every occurrence counts, so we scan the whole string and count each vowel character we find.
The simplest approach is to define the set of vowels (both cases), then filter the string's characters and count how many are in that set.
Here is the implementation:
We split the string into its individual characters, keep only those that appear in the vowels string, and return the length of the filtered result. The string vowels includes both lowercase and uppercase, so case does not matter.
Let us trace "apple". The letters a and e are vowels, so the count is 2. For "sky", none of the letters are vowels, so the count is 0. Repeated vowels each count separately, so careful scanning of the whole string is required.
The time complexity is O(n) because we visit each character once, and the space complexity is O(n) due to the split array (we could also count with a loop in O(1) space).
Best Answers
class Solution {
public int count_vowels(String s) {
int count = 0;
String vowels = "aeiouAEIOU";
for (char c : s.toCharArray()) {
if (vowels.indexOf(c) != -1) count++;
}
return count;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
