1. 題目描述python
給一個字符串,將字符串中先後對應的元音字母進行反轉,即左邊一半的元音字母與右邊一半元音字母鏡像反轉spa
Example 1: Input: "hello" Output: "holle" Example 2: Input: "leetcode" Output: "leotcede"
2. 解題代碼blog
class Solution: def reverseVowels(self, s: str) -> str: vowels = ['a','e','i','o','u','A','E','I','O','U'] lens = len(s) i = 0 j = lens-1 list_s = list(s) while i < j : #保證左邊索引不超過右邊 if list_s[i] not in vowels : #判斷左邊的元音字符,若是對應位置的字符不是元音字母,則索引加一 i += 1 #continue if list_s[j] not in vowels : #判斷右邊的元音字符,若是對應位置的字符不是元音字母,則索引減一 j -= 1 #continue if list_s[i] in vowels and list_s[j] in vowels : #判斷當次循環下索引i, j對應的字符是否同時是元音字母,若是是,則交換位置 list_s[i], list_s[j]= list_s[j], list_s[i] i += 1 j -= 1 return "".join(list_s) #將字符串的列表轉換爲字符串返回