Problem# Given a string s, remove the vowels 'a', 'e', 'i', 'o', and 'u'
from it, and return the new string.
Examples# Example 1:
1
2
Input: s = "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
1
2
Input: s = "aeiou"
Output: ""
Constraints:
1 <= s.length <= 1000s consists of only lowercase English letters.Solution# Method 1 - String Filtering# Intuition# We want to remove all vowels from the string. This can be done by iterating through the string and skipping any character that is a vowel.
Approach# Define a set of vowels. Build a new string by including only non-vowel characters. Code#
Cpp
Go
Java
Kotlin
Python
Rust
Typescript
1
2
3
4
5
6
7
8
9
10
#include <string>
using namespace std;
string removeVowels (string s) {
string res;
for (char c : s) {
if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' ) res += c;
}
return res;
}
1
2
3
4
5
6
7
8
9
10
func removeVowels (s string ) string {
vowels := map [byte ]bool {'a' : true , 'e' : true , 'i' : true , 'o' : true , 'u' : true }
res := make([]byte , 0 , len(s ))
for i := 0 ; i < len(s ); i ++ {
if !vowels [s [i ]] {
res = append(res , s [i ])
}
}
return string(res )
}
1
2
3
4
5
6
7
8
9
public class Solution {
public String removeVowels (String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray ()) {
if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' ) sb.append (c);
}
return sb.toString ();
}
}
1
2
3
fun removeVowels (s: String): String {
return s.filter { it !in "aeiou" }
}
1
2
def removeVowels (s: str) -> str:
return '' . join(c for c in s if c not in 'aeiou' )
1
2
3
fn remove_vowels (s: & str ) -> String {
s.chars().filter(|& c| ! "aeiou" .contains(c)).collect()
}
1
2
3
function removeVowels (s : string ): string {
return s .split ('' ).filter (c => ! 'aeiou' .includes (c )).join ('' );
}
Complexity# ⏰ Time complexity: O(N), where N is the length of s. 🧺 Space complexity: O(N), for the output string.