Remove Vowels from a String
Problem
Given a string s, remove all lowercase vowels from it. The vowels to remove are 'a', 'e', 'i', 'o', and 'u'. Return the new string after removing these vowels, keeping all other characters in their original order.
s = "leetcode""ltcd"def remove_vowels(s):
vowels = set("aeiou")
out = []
for c in s:
if c not in vowels:
out.append(c)
return "".join(out)
function removeVowels(s) {
const vowels = new Set(["a", "e", "i", "o", "u"]);
let out = "";
for (const c of s) {
if (!vowels.has(c)) out += c;
}
return out;
}
class Solution {
public String removeVowels(String s) {
StringBuilder out = new StringBuilder();
for (char c : s.toCharArray()) {
if ("aeiou".indexOf(c) == -1) out.append(c);
}
return out.toString();
}
}
string removeVowels(string s) {
string vowels = "aeiou";
string out;
for (char c : s) {
if (vowels.find(c) == string::npos) out += c;
}
return out;
}
Explanation
This is a straightforward filter: keep every character that is not a vowel, in the same order it appears. We do it in a single pass over the string.
First we put the five vowels into a set: vowels = set("aeiou"). A set gives instant membership checks, so testing c not in vowels is fast.
We walk through each character c; if it is not a vowel we add it to a list out. At the end we join the kept characters back into a string with "".join(out). Vowels are simply never added, which removes them while preserving the order of everything else.
Example: s = "leetcode". The vowels e, e, o, e are skipped, and l, t, c, d are kept in order, producing "ltcd".