LeetCode 0345. Reverse Vowels of a String反轉(zhuǎn)字符串中的元音字母【Easy】【Python】【雙指針】
題目
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
翻譯
編寫一個函數(shù)遇汞,以字符串作為輸入鳞仙,反轉(zhuǎn)該字符串中的元音字母。
示例 1:
輸入: "hello"
輸出: "holle"
示例 2:
輸入: "leetcode"
輸出: "leotcede"
說明:
元音字母不包含字母"y"碱茁。
思路
雙指針
left 指針從左往右找 元音字母
锁孟,right 指針從右往左找 元音字母
彬祖。
考慮到字符串不能改變,因此需要用 list
來替代品抽。
Python代碼
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
left, right = 0, len(s)-1 # 同時賦值
vowels = 'aeiou'
string = list(s) # 字符串不能改變, 所以要轉(zhuǎn)為 list
while left < right:
if string[left].lower() not in vowels: # lower 是取小寫
left += 1
elif string[right].lower() not in vowels:
right -= 1
else:
string[left], string[right] = string[right], string[left]
left += 1
right -= 1
return ''.join(string) # 將 string 中的元素以指定的字符連接生成一個新的字符串