Categories:

Tags:



Problem

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.

Constraints

  • 1 <= s.length <= 3 * 105
  • s consist of printable ASCII characters.

Solution

The problem Reverse Vowels of a String can be solved using two pointers to swap vowels from each end of string.

Implementation

class Solution
{
  public:
    bool isVowel(char ch) { return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; }

    string reverseVowels(string s)
    {
        int left = 0, right = s.length() - 1;
        while (left < right)
        {
            while (left < right && !isVowel(tolower(s[left])))
                left += 1;
            while (left < right && !isVowel(tolower(s[right])))
                right -= 1;

            swap(s[left++], s[right--]);
        }

        return s;
    }
};