Teaching Kids Programming: Videos on Data Structures and Algorithms
Given a string s, remove the vowels ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ from it, and return the new string.
Example 1:
Input: s = “leetcodeisacommunityforcoders”
Output: “ltcdscmmntyfrcdrs”Example 2:
Input: s = “aeiou”
Output: “”Constraints:
1 <= s.length <= 1000
s consists of only lowercase English letters.How to erase vowels in a string?
Loop over the string and check every character, if it is a vowel ignore it otherwise add it to the answer.
Python’s Function to Remove Vowels from a String
Let’s iterate each character and add it if it isn’t a vowel.
class Solution:
def removeVowels(self, s: str) -> str:
ans = ""
for i in s:
if i not in "aeiou":
ans += i
return ans
Let’s use a list and then join them:
class Solution:
def removeVowels(self, s: str) -> str:
ans = []
for i in s:
if i not in "aeiou":
ans.append(i)
return "".join(ans)
We could define the vowels as a set so the lookup time is faster:
class Solution:
def removeVowels(self, s: str) -> str:
ans = []
vowels = set("aeiou")
for i in s:
if i not in vowels:
ans.append(i)
return "".join(ans)
We can use Regex Expression:
class Solution:
def removeVowels(self, s: str) -> str:
return re.sub('a|e|i|o|u', '', s)
Or we can remove each vowel one by one:
class Solution:
def removeVowels(self, s: str) -> str:
for i in "aeiou":
s = s.replace(i, "")
return s
And we can use the list comprehension:
class Solution:
def removeVowels(self, s: str) -> str:
return "".join([c for c in s if c not in "aeiou"])
Using filter and lambda function to remove the vowels from a string in Python:
class Solution:
def removeVowels(self, s: str) -> str:
return "".join(filter(lambda x: x not in "aeiou", s))
See also: How to Remove Vowels of a String in C/C++?
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Sum of Digits in Base K
Next Post: Teaching Kids Programming - Algorithms to Compute the Range Sum of a Binary Search Tree