Remove the Vowels from a String
Solve this ProblemEasy5 min
Topics
BasicsStrings
Companies
TCSInfosysWipro
Given a string
text, return it with every vowel (a, e, i, o, u, in either case) removed. All other characters keep their order.
This combines the filtering idea from removing spaces with the vowel test from counting vowels. The second solution introduces regular expressionsRegular ExpressionA compact pattern language for describing text to find or replace, e.g. [aeiou] means "any one of these letters"., a compact way to say "remove anything matching this pattern" that most languages support.
Test Case 1:
Input:text = "Education"
Output:"dctn"
Explanation:E, u, a, i, o are dropped — capital vowels too.
Test Case 2:
Input:text = "rhythm"
Output:"rhythm"
Explanation:No vowels to remove.
Constraints
- ◆
1 ≤ text.length ≤ 1000 - ◆
text contains printable ASCII characters
Try the Dry Run
Approach & Solutions
Keep Characters Not in the Vowel ListGood
Walk through the text and copy each character unless it appears in the vowel list "aeiouAEIOU". Everything else — consonants, digits, spaces and punctuation — is kept in its original order.
Time
O(n)Space
O(n)Java
class Solution {
public String removeVowels(String text) {
StringBuilder result = new StringBuilder();
for (char ch : text.toCharArray()) {
if ("aeiouAEIOU".indexOf(ch) < 0) {
result.append(ch);
}
}
return result.toString();
}
}Pattern-Based RemovalOptimal
Describe what to remove and let the library do the work: a regular expression [aeiouAEIOU] with replaceAll in Java, a case-insensitive /[aeiou]/gi in JavaScript, a generator with join in Python, and remove_if with a lambda in C++. C keeps the filtering loop.
Time
O(n)Space
O(n)Java
class Solution {
public String removeVowels(String text) {
return text.replaceAll("[aeiouAEIOU]", "");
}
}