对撞指针
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = ['a', 'e', 'i', 'o', 'u']
left = 0
right = len(s) - 1
str_list = [x for x in s]
while left < right:
if str_list[left].lower() not in vowels:
left += 1
continue
if str_list[right].lower() not in vowels:
right -= 1
continue
self.swap(str_list, left, right)
left += 1
right -= 1
return ''.join(str_list)
def swap(self, arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
复杂度分析
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)