Monday, June 26, 2017

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



Solution:

Use a HashSet to store all vowels.

Use two pointers from two side of the string and go towards each other.

If any of the pointers point to a non-vowel character, it advances.

Now two pointers point to two vowels. Swap them and update the pointers.

Keep going until these two pointers meet.



Code:


public class Solution {
    public String reverseVowels(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        HashSet<Character> set = new HashSet<>();
        set.add('a');
        set.add('e');
        set.add('i');
        set.add('o');
        set.add('u');
        set.add('A');
        set.add('E');
        set.add('I');
        set.add('O');
        set.add('U');
        char[] arr = s.toCharArray();
        int i = 0;
        int j = arr.length - 1;
        while (i < j) {
            if (!set.contains(arr[i])) {
                i++;
                continue;
            }
            if (!set.contains(arr[j])) {
                j--;
                continue;
            }
            swap(arr, i, j);
            i++;
            j--;
        }
        return new String(arr);
    }
    public void swap(char[] arr, int i, int j) {
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}