Reverse Vowels of a String
Question
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1: Given s = "hello", return "holle".
Example 2: Given s = "leetcode", return "leotcede".
Note: The vowels does not include the letter "y".
Tags
- String
- Two Pointers
Thought
Use two pointers start from the head and tail respectively. Swap if both of the pointers pointing to the vowels.
Code
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = 'aeiouAEIOU'
start, end = 0, len(s) - 1
sList = list(s)
while start < end:
while start < end and sList[start] not in vowels:
start += 1
while start < end and sList[end] not in vowels:
end -= 1
sList[start], sList[end] = sList[end], sList[start]
start += 1
end -= 1
return ''.join(sList)