Count Vowels and Consonants in a String
Solve this ProblemEasy10 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text, return [vowels, consonants]: how many letters are vowels (a, e, i, o, u, in either case) and how many letters are consonants. Characters that are not letters are not counted.
Two details make this more than a simple loop. Letters come in two casesLetter CaseUpper case (A–Z) and lower case (a–z) versions of the same letters, stored as different character codes., so "E" and "e" must be treated alike; and only letters belong to either group. A lookup stringLookup StringA short string listing the allowed characters, used with indexOf / in / includes to test membership. such as "aeiouAEIOU" handles the first point in one test.
Test Case 1:
Input:text = "Hello World"
Output:[3, 7]
Explanation:e, o, o are vowels; H, l, l, W, r, l, d are consonants; the space is neither.
Test Case 2:
Input:text = "2 + 2"
Output:[0, 0]
Explanation:No letters at all.
Constraints
- ◆
1 ≤ text.length ≤ 200 - ◆
text contains printable ASCII characters
Try the Dry Run
Approach & Solutions
Compare with Each VowelGood
Lower-case each character so 'A' and 'a' are treated alike. If it is a letter, compare it with a, e, i, o and u: a match is a vowel, anything else is a consonant. Characters that are not letters count as neither.
Time
O(n)Space
O(1)Java
class Solution {
public int[] countVowelsConsonants(String text) {
int vowels = 0, consonants = 0;
for (char ch : text.toCharArray()) {
char c = Character.toLowerCase(ch);
if (c >= 'a' && c <= 'z') {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
} else {
consonants++;
}
}
}
return new int[] {vowels, consonants};
}
}Look Up a Vowel StringOptimal
Keep all ten vowels, upper and lower case, in one string "aeiouAEIOU" and ask whether the character appears in it (indexOf / in / find / strchr / includes). If not, and it is a letter, it is a consonant. One membership test replaces five comparisons.
Time
O(n)Space
O(1)Java
class Solution {
public int[] countVowelsConsonants(String text) {
int vowels = 0, consonants = 0;
for (char ch : text.toCharArray()) {
if ("aeiouAEIOU".indexOf(ch) >= 0) {
vowels++;
} else if (Character.isLetter(ch)) {
consonants++;
}
}
return new int[] {vowels, consonants};
}
}