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".

string reverseVowels(string s)  { // time: O(n); space: O(1)
    int n = s.length();
    if (n <= 1) return s;
    string vowels = "aeiouAEIOU";
    int i = 0, j = n - 1;
    while (i < j) {
        while (i < j && vowels.find(s[i]) == string::npos) ++i;
        while (i < j && vowels.find(s[j]) == string::npos) --j;
        swap(s[i++], s[j--]);
    }
    return s;
}
bool isVowel(char ch) {
    ch = tolower(ch);
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true;
    else return false;
}
string reverseVowels(string s) { // time: O(n); space: O(1)
    int n = s.length();
    if (n <= 1) return s;
    int i = 0, j = n - 1;
    while (i < j) {
        while (i < j && !isVowel(s[i])) ++i;
        while (i < j && !isVowel(s[j])) --j;
        swap(s[i++], s[j--]);
    }
    return s;
}

Last updated

Was this helpful?