Reverse Vowels of a String

345. Reverse Vowels of a String

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

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

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

public class Solution {
    public String reverseVowels(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        
        int i = 0, j = s.length() - 1;
        char[] chars = s.toCharArray();
        
        while (i < j) {
            if (!isVowel(chars[i])) {
                i++;
                continue;
            }
            if (!isVowel(chars[j])) {
                j--;
                continue;
            }
            
            if (i < j) {
                char temp = chars[i];
                chars[i] = chars[j];
                chars[j] = temp;
            
                i++;
                j--; 
            }
        }
        
        return new String(chars);
    }
    
    private boolean isVowel(char c) {
        c = Character.toLowerCase(c);
        
        return c == 'a' || c == 'e' || c == 'i'
                || c == 'o' || c == 'u';
    }
}

Hope this helps,
Michael

DigitalOcean Referral Badge