Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

Input: "hello"
Output: "holle"

Example 2:

Input: "leetcode"
Output: "leotcede"

Note: The vowels does not include the letter "y".

class Solution {
    public boolean isVowel(char c) {
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O'
                || c == 'U')
            return true;
        return false;
    }

    public String reverseVowels(String s) {
        int i = 0, j = s.length() - 1;
        char[] str = s.toCharArray();
        while (i < j) {
            while (i < str.length && i < j && !isVowel(str[i]))
                i++;
            while (j >= 0 && j > i && !isVowel(str[j]))
                j--;
            if (i != j) {
                char t = str[i];
                str[i] = str[j];
                str[j] = t;
                i++;
                j--;
            }
        }
        return new String(str);
    }
}

Last updated