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 = "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"
Constraints:
1 <= s.length <= 3 * 105
s consist of printable ASCII characters.
Solutions
Solution 1: Two Pointers
Thinking
Reverse only vowels; consonants stay. Extracting vowels uses extra memory. The same two-pointer swap applies, but only on vowels.
Skip non-vowels from both ends, swap while \(i<j\), and shrink. A small vowel set handles case.
We can use two pointers \(i\) and \(j\), initially pointing to the start and end of the string respectively.
In each loop, we check whether the character at \(i\) is a vowel. If it's not, we move \(i\) forward. Similarly, we check whether the character at \(j\) is a vowel. If it's not, we move \(j\) backward. If \(i < j\) at this point, then both characters at \(i\) and \(j\) are vowels, so we swap these two characters. Then, we move \(i\) forward and \(j\) backward. We continue the above operations until \(i \ge j\).
The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(|\Sigma|)\), where \(\Sigma\) is the size of the character set.