Reverse Vowels of a String

Problem

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".

Solution

public class Solution {

    public String reverseVowels(String s) {
        if (s == null || s.length() < 2) return s;
        String vowels = "aeiouAEIOU";
        char[] chars = s.toCharArray();
        int start = 0, end = s.length() - 1;
        while (start < end) {
            //Better using while than if statement here 
            while(start < end && vowels.indexOf(chars[start]) == -1) start++;
            while(start < end && vowels.indexOf(chars[end]) == -1) end--;
            //Do swap, and do not forget to update both the start and the end 
            char temp = chars[start];
            chars[start++] = chars[end];
            chars[end--] = temp;
        }
        return String.valueOf(chars);
    }
}

Analysis

Typical reverse solution using two pointers
We use while loop to pass over the non-vowels char
Notice that we have a String of vowels and we use vowels.indexOf(char) to check the vowel
This is much better than using '!=' to each vowel ;)

results matching ""

    No results matching ""