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

public class Solution {
    public String reverseVowels(String s) {
        //Create a vowel list
        ArrayList<Character> vowList = new ArrayList<Character>();
        //put all vowel in the list
        vowList.add('a');
        vowList.add('e');
        vowList.add('i');
        vowList.add('o');
        vowList.add('u');
        vowList.add('A');
        vowList.add('E');
        vowList.add('I');
        vowList.add('O');
        vowList.add('U');

        //transfer the string s into an array
        char[] arr = s.toCharArray(); 

        int i = 0; //begining
        int j = s.length() - 1; //end

        while (i < j) {
            //Check if the ith character is not in the list, continue;
            if (!vowList.contains (arr[i])) {
                i++;
                continue;
            }
            //Check if the jth character is not in the list, continue;
            if (!vowList.contains (arr[j])) {
                j--;
                continue;
            }

            //If both of the characters are in the list, swap them
            char tmp =arr[i];
            arr[i] = arr[j];
            arr[j] = tmp; 

            i++;
            j--;
        }
        return new String(arr);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s