题目地址:1119. Remove Vowels from a String
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
这道题目是easy难度的,题目也容易理解,做起来也快。
Python第一版解决如下:
class Solution:
def removeVowels(self, S: str) -> str:
return S.replace("a","").replace("e","").replace("i","").replace("o","").replace("u","")
只超过了20%的人,改进后的做法如下:
class Solution:
def removeVowels(self, S: str) -> str:
res=''
a={'a','e','i','o','u'}
for i in S:
if i not in a:
res+=i
return res
现在就超过了90%的人,我想不到更快的解法了。
Java解法如下:
class Solution {
public String removeVowels(String S) {
return S.replaceAll("[aeiou]", "");
}
}
C++解法如下:
class Solution {
public:
string removeVowels(string S) {
set<char> vowels = {'a', 'e', 'i', 'o', 'u'};
string result = "";
for (int i = 0; i < S.size(); i++) {
if (vowels.find(S[i]) != vowels.end()) {
continue;
} else {
result += S[i];
}
}
return result;
}
};