345. 反转字符串中的元音字母


双指针法

class Solution {
    public String reverseVowels(String s) {

        /**
         * 双指针法遍历字符串
         * s.toCharArray()方法将字符串转为字符数组
         * new String(chars)将字符数组转换为字符串(直接用toString()打印的是对象名)
         */
        char temp;
        char[] chars = s.toCharArray();
        int left = 0;
        int right = chars.length - 1;

        while (left < right){

            if (! judge(chars[left])){
                left++;
            }
            else if (! judge(chars[right])){
                right--;
            }
            else {

                temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                left++;
                right--;
            }
        }

        return new String(chars);
    }

    public boolean judge(char c){

        if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U'){
            return true;
        }

        return false;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

优化1——简化判断语句

class Solution {
    public String reverseVowels(String s) {

        /**
         * 双指针法遍历字符串
         * s.toCharArray()方法将字符串转为字符数组
         * new String(chars)将字符数组转换为字符串(直接用toString()打印的是对象名)
         */
        char temp;
        char[] chars = s.toCharArray();
        int left = 0;
        int right = chars.length - 1;

        while (left < right){

            if (! judge(chars[left])){
                left++;
            }
            else if (! judge(chars[right])){
                right--;
            }
            else {

                temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                left++;
                right--;
            }
        }

        return new String(chars);
    }

    public boolean judge(char c){

        /**
         * 如果该字符不在该字符串内,则返回-1
         */
        return "aeiouAEIOU".indexOf(c) >= 0;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/reverse-vowels-of-a-string/