345. Reverse Vowels of a String
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".
Solution: Two Pointers
VOWELS = set('aeiouAEIOU')
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
chars = list(s)
low = 0
high = len(chars) - 1
while low < high:
if chars[low] not in VOWELS:
low += 1
elif chars[high] not in VOWELS:
high -= 1
else:
chars[low], chars[high] = chars[high], chars[low]
low += 1
high -= 1
return ''.join(chars)
Lessons:
- Reverse: use two pointers!