LeetCode 345. Reverse Vowels of a String
Published in
Mar 29, 2021
題目:
將string裡面的母音aeiou做reverse。
Example 1:
Input: s = "hello"
Output: "holle"
Example 2:
Input: s = "leetcode"
Output: "leotcede"
思路:
- 先建立查找母音的reference
vowels=”aeiou” - 將原本input的string變成list,方便一個一個查找
string = list(s) - 從最左邊與最右邊起始值開始,寫個while loop
i, j = 0, len(s)-1 - while i<j: (往中間靠攏)
判斷是不是母音
if string[i].lower() not in vowels:
i +=1
elif string[j].lower() not in vowels:
j-=1
else:
string[i], string[j] = string[j], string[i]
i+=1
j-=1 - return “”.join(string) 把單字重新組起來。
Coding:
class Solution:
def reverseVowels(self, s: str) -> str:
vowels="aeiou"
string = list(s)
i, j = 0, len(s)-1
while i < j:
if string[i].lower() not in vowels:
i+=1
elif string[j].lower() not in vowels:
j-=1
else:
string[i],string[j] = string[j], string[i]
i+=1
j-=1
return "".join(string)