Here’s a Python function that reverses only the vowels in a string while keeping the rest of the characters in place
def reverse_vowels(s):
# Define vowels
vowels = "aeiouAEIOU"
# Convert the string to a list to modify it
s_list = list(s)
# Initialize two pointers
left, right = 0, len(s) - 1
# Traverse from both ends to find vowels and swap them
while left < right:
# Move the left pointer to the next vowel
while left < right and s_list[left] not in vowels:
left += 1
# Move the right pointer to the previous vowel
while left < right and s_list[right] not in vowels:
right -= 1
# Swap the vowels
s_list[left], s_list[right] = s_list[right], s_list[left]
# Move both pointers inward
left += 1
right -= 1
# Join the list back into a string and return it
return ''.join(s_list)
Explanation:
- Initialize Pointers: Use two pointers, one starting from the left (
left
) and one from the right (right
). - Identify Vowels: Move each pointer until it finds a vowel.
- Swap Vowels: Once both pointers are at vowels, swap them.
- Continue Until Overlap: Repeat the process until
left
andright
pointers cross each other. - Return Result: Convert the list back to a string and return it.
print(reverse_vowels("hello")) # Output: "holle"
print(reverse_vowels("leetcode")) # Output: "leotcede"
Here’s another explanation for the function:
- Identify Vowels: We define vowels as the characters “a, e, i, o, u” (both uppercase and lowercase).
- Convert String to List: Since strings in Python are immutable (they can’t be modified in place), we convert the string to a list of characters,
s_list
, so that we can swap vowels within it. - Use Two Pointers: We set two pointers—
left
at the start andright
at the end of the list. Theleft
pointer will move from the beginning, and theright
pointer will move from the end of the string. Both pointers will work towards each other until they meet in the middle. - Move to Vowels:
- The
left
pointer moves forward until it finds a vowel (if it’s not a vowel, it keeps moving right). - Similarly, the
right
pointer moves leftward until it finds a vowel.
- Swap the Vowels: Once both pointers are at vowels, we swap the characters at
left
andright
ins_list
. This reverses the positions of the vowels without changing the position of any other characters. - Repeat Until Pointers Cross: After swapping, we move the
left
pointer one step right and theright
pointer one step left. The loop continues untilleft
andright
cross each other, meaning all vowels have been reversed. - Join List into String: Finally, we join the list back into a single string and return it. The non-vowel characters stay in their original positions, while only the vowels are reversed.
Example Walkthrough
For the input "hello"
:
left
finds the vowel'e'
, andright
finds the vowel'o'
.- These vowels are swapped, resulting in
"holle"
. - After the swap,
left
andright
pointers meet, and the final string with reversed vowels is returned:"holle"
.