We use two pointers l and r at the ends of the string. We skip non-vowel characters and swap the vowels at l and r.
- Convert string to list
s_list. l = 0,r = len(s) - 1.vowels = set("aeiouAEIOU").- While
l < r:- While
l < rands_list[l]not invowels:l += 1. - While
l < rands_list[r]not invowels:r -= 1. - Swap
s_list[l]ands_list[r]. l += 1,r -= 1.
- While
- Return
".join(s_list)`.
- Time Complexity: O(N).
- Space Complexity: O(N) (due to list conversion).
def reverse_vowels(s):
vowels = set("aeiouAEIOU")
s = list(s)
l, r = 0, len(s) - 1
while l < r:
if s[l] not in vowels:
l += 1
elif s[r] not in vowels:
r -= 1
else:
s[l], s[r] = s[r], s[l]
l += 1
r -= 1
return "".join(s)