Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/1119.html
1119. Remove Vowels from a String
Level
Easy
Description
Given a string S
, remove the vowels 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
from it, and return the new string.
Example 1:
Input: “leetcodeisacommunityforcoders”
Output: “ltcdscmmntyfrcdrs”
Example 2:
Input: “aeiou”
Output: “”
Note:
S
consists of lowercase English letters only.1 <= S.length <= 1000
Solution
Create a new string and append only consonants to the new string. Use a StringBuffer
, which is initially empty, and loop over the original string S
and add the consonants to the StringBuffer
. Finally, return the string converted from the StringBuffer
.
-
class Solution { public String removeVowels(String S) { StringBuffer sb = new StringBuffer(); int length = S.length(); for (int i = 0; i < length; i++) { char c = S.charAt(i); if (!isVowel(c)) sb.append(c); } return sb.toString(); } public boolean isVowel(char letter) { return letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u'; } }
-
// OJ: https://leetcode.com/problems/remove-vowels-from-a-string/ // Time: O(N) // Space: O(1) extra space class Solution { public: string removeVowels(string s) { string ans; for (char c : s) { if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u') ans += c; } return ans; } };
-
class Solution: def removeVowels(self, s: str) -> str: res = [] for c in s: if c not in {'a', 'e', 'i', 'o', 'u'}: res.append(c) return ''.join(res)
-
func removeVowels(s string) string { ans := []rune{} for _, c := range s { if !(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { ans = append(ans, c) } } return string(ans) }
-
function removeVowels(s: string): string { return s.replace(/[aeiou]/g, ''); }