LeetCode 345. Reverse Vowels of a String

881 ワード

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".
Only Swap vowels.
    bool isVowels(char a) {
        char b = tolower(a);
        return (b == 'a') || (b == 'e') || (b == 'i') || (b == 'o') || (b == 'u');
    }
    string reverseVowels(string s) {
        if(s.size() <= 1) return s;
        int i = 0;
        int j = s.size() - 1;
        while(i <= j) {
            if(isVowels(s[i]) && isVowels(s[j])) {
                swap(s[i], s[j]);
                i++;
                j--;
            }
            if(!isVowels(s[i])) i++;
            if(!isVowels(s[j])) j--;
        }
        return s;
    }