題目


Given a string s, remove the vowels ‘a’, ’e’, ‘i’, ‘o’, and ‘u’ from it, and return the new string.

Example 1:

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

Example 2:

1Input: s = "aeiou"
2Output: ""

Constraints:

  • 1 <= s.length <= 1000
  • s consists of only lowercase English letters.

我的思路


由於是將一個 String 中所有的母音都移除,所以我們直接建立一個新的 StringBuilder,將 Input loop 一遍,如果不是母音的話就加入到 StringBuilder 裡面,最後返回 String

Note: 如果不知道為什麼要使用 StringBuilder,可以 google “String concat vs StringBuilde”。

程式碼


 1class Solution {
 2    public String removeVowels(String s) {
 3        StringBuilder result = new StringBuilder();
 4        
 5        for(char c : s.toCharArray()) {
 6            if (!isVowels(c)) {
 7                result.append(c);
 8            }
 9        }
10        return result.toString();
11    }
12    
13    public boolean isVowels(char c) {
14        if (c == 'a' ||
15            c == 'e' ||
16            c == 'i' ||
17            c == 'o' ||
18            c == 'u') {
19            return true;
20        }
21        return false;
22    }
23}