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.
0
to 3 * 10^5
.Identify Vowels: Create a set of vowels for quick lookup.
String Conversion: Since strings in Python are immutable, convert the string to a list of characters to facilitate swapping.
def reverseVowels(s: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
s = list(s) # Convert string to a list for mutability
left = 0
right = len(s) - 1
while left < right:
if s[left] not in vowels:
left += 1
elif s[right] not in vowels:
right -= 1
else:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return ''.join(s)
# Example Usage
print(reverseVowels("hello")) # Output: "holle"
print(reverseVowels("leetcode")) # Output: "leotcede"
This method efficiently reverses the vowels in the given string while preserving the positions of the non-vowel characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?