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:

  1. S consists of lowercase English letters only.
  2. 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';
    }
}

All Problems

All Solutions