Given a string s, reverse only the vowels in the string and return the resulting string.
The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both lowercase and uppercase, potentially more than once.
Constraints:
s.length
s consists of printable ASCII characters.
The key intuition behind this solution is to use the Two Pointers pattern to efficiently reverse only the vowels in the string without disturbing the positions of consonants and other characters. We place one pointer at the beginning (left) and one at the end (right) of the string. Both pointers move toward each other: the left pointer skips over non-vowel characters moving forward, and the right pointer skips over non-vowel characters moving backward. When both pointers land on vowels, we swap those two vowels and continue moving inward. This effectively reverses the order of vowels in-place while leaving all other characters untouched.
Now, let’s look at the solution steps below:
Define a set vowels containing all lowercase (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and uppercase vowels (‘A’, ‘E’, ‘I’, ‘O’, ‘U’) for
Given a string s, reverse only the vowels in the string and return the resulting string.
The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both lowercase and uppercase, potentially more than once.
Constraints:
s.length
s consists of printable ASCII characters.
The key intuition behind this solution is to use the Two Pointers pattern to efficiently reverse only the vowels in the string without disturbing the positions of consonants and other characters. We place one pointer at the beginning (left) and one at the end (right) of the string. Both pointers move toward each other: the left pointer skips over non-vowel characters moving forward, and the right pointer skips over non-vowel characters moving backward. When both pointers land on vowels, we swap those two vowels and continue moving inward. This effectively reverses the order of vowels in-place while leaving all other characters untouched.
Now, let’s look at the solution steps below:
Define a set vowels containing all lowercase (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and uppercase vowels (‘A’, ‘E’, ‘I’, ‘O’, ‘U’) for