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

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """

        vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
        s = list(s)
        left, right = 0, len(s) - 1

        while left < right:
            while left < right and s[left] not in vowels:
                left += 1

            while left < right and s[right] not in vowels:
                right -= 1

            if s[left] in vowels and s[right] in vowels:
                s[left], s[right] = s[right], s[left]
                left += 1
                right -= 1
            else:
                break

        return ''.join(s)

Last updated