Description
Reverse Vowels of a String - LeetCode
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.
Examples
Example 1:
Input: s = “IceCreAm”
Output: “AceCreIm”
Explanation:
The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, s becomes "AceCreIm".
Example 2:
Input: s = “leetcode” Output: “leotcede”
Constraint
sconsist of printable ASCII characters.
Code
class Solution {
public:
string reverseVowels(string s) {
string word = s;
int front = 0;
int back = s.length() - 1;
const string vowels = "aeiouAEIOU";
while(front < back){
bool frontOK = vowels.find(word[front]) != string::npos;
bool backOK = vowels.find(word[back]) != string::npos;
if (frontOK && backOK) {
swap(word[front], word[back]);
front++;
back--;
}
if (!frontOK) front++;
if (!backOK) back--;
}
return word;
}
};Approach
- Create result
word,front,back, andvowelsvariables - Loop through with 2 pointers until there the
frontis ahead of theback- Check if both
frontandbackare both vowels- Swap the
frontandback - Update
frontandback
- Swap the
- Check if
frontis a vowel- Update
front
- Update
- Check if
backis a vowel- Update
back
- Update
- Check if both
- Return the result
word