- Set two pointers to find all vowels and reverse them
- Find all vowels and use regex to replace it (re.sub)
O(n)
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vocab = set(['a','e','i','o','u','A','E','I','O','U'])
s = list(s)
n = len(s)
head = 0
tail = n - 1
while head < tail:
while head < tail and s[head] not in vocab:
head += 1
while tail > head and s[tail] not in vocab:
tail -= 1
if head < tail:
s[head], s[tail] = s[tail], s[head]
head += 1
tail -= 1
return "".join(s)
def reverseVowels2(self, s):
vowels = re.findall('(?i)[aeiou]', s)
return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)