345. Reverse Vowels of a String - Easy

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

 

use two pointers

naive solution:

class Solution {
    public String reverseVowels(String s) {
        Set<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[] c = s.toCharArray();
        int i = 0, j = c.length - 1;
        while(i < j) {
            if(set.contains(c[i]) && set.contains(c[j])) {
                swap(c, i++, j--);
            } else if(set.contains(c[i])) {
                j--;
            } else if(set.contains(c[j])) {
                i++;
            } else {
                i++;
                j--;
            }
        }
        return new String(c);
    }
    
    private void swap(char[] c, int i, int j) {
        char tmp = c[i];
        c[i] = c[j];
        c[j] = tmp;
    }
}

 

optimized

 

class Solution {
    public String reverseVowels(String s) {
        Set<Character> set = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        
        char[] c = s.toCharArray();
        int i = 0, j = c.length - 1;
        while(i < j) {
            while(i < j && !set.contains(c[i])) {
                i++;
            }
            while(i < j && !set.contains(c[j])) {
                j--;
            }
            char tmp = c[i];
            c[i] = c[j];
            c[j] = tmp;
            
            i++;
            j--;
        }
        return new String(c);
    }
}

 

posted @ 2019-08-12 12:07  fatttcat  阅读(104)  评论(0编辑  收藏  举报