String - 345. Reverse Vowels of a String

时间:2022-07-25
本文章向大家介绍String - 345. Reverse Vowels of a String,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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:

Input: "hello" Output: "holle"

Example 2:

Input: "leetcode" Output: "leotcede"

Note: The vowels does not include the letter "y".

思路: 只翻转元音字母,就只用两个指针,首尾移动来翻转元音字母。

代码:

java:

class Solution {

    public static boolean[] vowels = new boolean[256];
    static{
        vowels['a'] = true;
        vowels['o'] = true;
        vowels['e'] = true;
        vowels['i'] = true;
        vowels['u'] = true;
        vowels['A'] = true;
        vowels['O'] = true;
        vowels['E'] = true;
        vowels['I'] = true;
        vowels['U'] = true;
    }

    public String reverseVowels(String s) {
        if(s == null || s.isEmpty()) return "";

        int i = 0, j = s.length() - 1;
        char[] str = s.toCharArray();
        
        while(i < j) {
            while(i < j && !vowels[str[i]]) i++;
            while(i < j && !vowels[str[j]]) j--;
            if(i < j) {
                char temp = str[i];
                str[i++] = str[j];
                str[j--] = temp;
            }
        }
        return String.valueOf(str);
    }
}