345. Reverse Vowels of a String - jiejackyzhang/leetcode-note GitHub Wiki
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".
String类题目。
解题思路为双指针,从左右分别进行,左右指针都为vowel时,则交换彼此的字符。
public class Solution {
    private static final String vowels = "aeiouAEIOU";
    
    private void swap(char[] a, int i, int j) {
        char temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    
    public String reverseVowels(String s) {
        if(s == null || s.length() == 0 ||s.length() == 1) return s;
        char[] array = s.toCharArray();
        int i = 0, j = array.length-1;
        while(i < j) {
            if(vowels.indexOf(array[i]) == -1) {
                i++;
                continue;
            }
            if(vowels.indexOf(array[j]) == -1) {
                j--;
                continue;
            }
            swap(array, i, j);
            i++;
            j--;
        }
        return new String(array);
    }
}