常规的双指针题目,需要注意的是,Python中str是不可变类型,所以要先将str转换为其他类型,比如list
注:把vowels由list改为set后,快了不止一点,应该是涉及到list和set的存储方式问题。
Python代码
def reverseVowels(self, s: str) -> str:
vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
slist = list(s)
low, high = 0, len(s)-1
while low <= high:
if slist[low] in vowels and slist[high] in vowels:
slist[low], slist[high] = slist[high], slist[low]
low += 1
high -= 1
else:
if slist[low] not in vowels:
low += 1
if slist[high] not in vowels:
high -= 1
return ''.join(slist)