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:

1
2
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"

Example 2:

1
2
Input: "aeiou"
Output: ""

Note:

  1. S consists of lowercase English letters only.
  2. 1 <= S.length <= 1000

解法

解法一:

使用字符串的replace方法,将所有元音字母替换成””。

Java

1
2
3
String removeVowels(String str) {
return str.replaceAll("a", "").replaceAll("e", "").replaceAll("i", "").replaceAll("o", "").replaceAll("u", "");
}

解法二:

所有元音作为一个集合,遍历s里面的所有字符,遇到元音就跳过,最后构造一个新的字符串返回

JAVA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
String removeVowels(String str) {
Set<Character> vowels = new HashSet<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');

StringBuilder stringBuilder = new StringBuilder();
for (char c : str.toCharArray()) {
if (vowels.contains(c)) {
continue;
}
stringBuilder.append(c);
}
return stringBuilder.toString();
}
0%