LeetCode 1119. Remove Vowels from a String
原题链接在这里:https://leetcode.com/problems/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: s = "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: s = "aeiou" Output: ""
Constraints:
1 <= s.length <= 1000sconsists of only lowercase English letters.
题解:Check each character of string, if it is vowel, skip it. Otherwise, add it to the new string.
Time Complexity: O(n). n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public String removeVowels(String s) { 3 if (s == null || s.length() == 0){ 4 return s; 5 } 6 7 HashSet<Character> hs = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u')); 8 StringBuilder sb = new StringBuilder(); 9 for(int i = 0; i < s.length(); i++){ 10 char c = s.charAt(i); 11 if (hs.contains(c)){ 12 continue; 13 } 14 15 sb.append(c); 16 } 17 18 return sb.toString(); 19 } 20 }
浙公网安备 33010602011771号