← All problems

345. Reverse Vowels of a String

EasyOpen on LeetCodeProblem statement

Problem Statement

345. Reverse Vowels of a String

Easy


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.

 

Example 1:

Input: s = "hello"
Output: "holle"

Example 2:

Input: s = "leetcode"
Output: "leotcede"

 

Constraints:

C++

Source file
class Solution {
public:
    string reverseVowels(string s) {
        int lt=0, rt=s.size()-1;
        unordered_set<char> vowel = {'a','e','i','o','u','A','E','I','O','U'};
        while (lt<rt){
            while(lt<rt && vowel.find(s[lt])==vowel.end())   lt++;
            while(lt<rt && vowel.find(s[rt])==vowel.end())   rt--;
            if(lt<rt)   swap(s[lt], s[rt]);
            lt++, rt--;
        }
        return s;
    }
};