This problem requires removing vowels ('a', 'e', 'i', 'o', 'u') from a given string and returning the modified string. The solutions presented use a straightforward iterative approach and a more concise regular expression approach (where available).
This approach iterates through each character of the input string. If a character is not a vowel, it's appended to a new string which is then returned.
Time Complexity: O(n), where n is the length of the input string. We iterate through the string once.
Space Complexity: O(n) in the worst case (no vowels present, resulting in a copy of the entire string). O(m) in average case, where 'm' is the number of consonants, which is generally less than 'n'. If we consider the space used to store the result string, the space complexity is O(n) in the worst case. If we don't consider the space used to store the result string, then space complexity would be O(1).
Code Implementation:
Python:
class Solution:
def removeVowels(self, s: str) -> str:
vowels = "aeiou"
result = ""
for char in s:
if char not in vowels:
result += char
return result
Java:
class Solution {
public String removeVowels(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (!"aeiou".contains(String.valueOf(c))) {
sb.append(c);
}
}
return sb.toString();
}
}
C++:
class Solution {
public:
string removeVowels(string s) {
string result = "";
for (char c : s) {
if (string("aeiou").find(c) == string::npos) {
result += c;
}
}
return result;
}
};
Go:
func removeVowels(s string) string {
result := ""
for _, char := range s {
if !strings.ContainsRune("aeiou", char) {
result += string(char)
}
}
return result
}
Languages like JavaScript, Python, and others provide built-in regular expression support. This allows for a more concise solution.
Time Complexity: The time complexity depends on the regex engine's implementation but is generally considered O(n) in most practical scenarios.
Space Complexity: Similar to approach 1, the space complexity is O(n) in the worst-case scenario (no vowels) and O(m) on average where m is the number of consonants. Ignoring the space complexity of the output string, the space complexity is O(1).
Code Implementation:
Python:
import re
class Solution:
def removeVowels(self, s: str) -> str:
return re.sub(r'[aeiou]', '', s)
JavaScript:
function removeVowels(s) {
return s.replace(/[aeiou]/g, '');
}
TypeScript:
function removeVowels(s: string): string {
return s.replace(/[aeiou]/g, '');
}
Note: The regular expression approach is generally more efficient and readable when available, though the iterative approach provides better understanding of the fundamental string manipulation techniques and is more portable across different programming languages with varying regex support. The choice depends on coding style preferences and project requirements.