[LC] 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"


class Solution {
    public String reverseVowels(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        char[] charArr = s.toCharArray();
        int start = 0, end = charArr.length - 1;
        while (start < end) {
            if (!isVowel(charArr[start])) {
                start += 1;
            } else if (!isVowel(charArr[end])) {
                end -= 1;
            } else {
                char tmp = charArr[start];
                charArr[start] = charArr[end];
                charArr[end] = tmp;
                start += 1;
                end -= 1;
            }
        }
        return new String(charArr);
    }
    
    private boolean isVowel(Character c) {
        return c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U';
    }
}

 

你可能感兴趣的:([LC] 345. Reverse Vowels of a String)