文章 224
评论 6
浏览 200766
String - 345. Reverse Vowels of a String

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);
    }
}

标题:String - 345. Reverse Vowels of a String
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/06/28/1561735304598.html

Nothing just happens, it's all part of a plan.

取消