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: Given s = "hello", return "holle".

Example 2: Given s = "leetcode", return "leotcede".

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

The Idea:

  • Swap the first and back occurances respectively.

string reverseVowels(string s) {

    unordered_set<char> vowels = { 'a', 'e', 'i', 'o', 'u',
                                 'A', 'E', 'I', 'O', 'U'};

    int iter_front = 0;
    int iter_back = s.size() - 1;


    while (iter_front < iter_back) {

        while (iter_front < iter_back && vowels.find(s[iter_front]) == vowels.end())
            iter_front++;
        while (iter_front < iter_back && vowels.find(s[iter_back]) == vowels.end())
            iter_back--;

        swap(s[iter_front], s[iter_back]);
        iter_front++;
        iter_back--;
    }

    return s;
}


int main() {

    string s = "hello";
    cout << reverseVowels(s) << endl;

    return 0;
}

Python

Last updated

Was this helpful?