Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
思路:
設(shè)置一個(gè)list存放所有的元音字母,共計(jì)十個(gè)。設(shè)置兩個(gè)游標(biāo)分別從左右兩次計(jì)數(shù),不是元音字母,繼續(xù)向中間移動(dòng),如果遇到元音字母,就和另一個(gè)方向的元音字母交換。直到游標(biāo)相遇為止。
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
low, high = 0, len(s)-1
list_s = list(s)
while(low < high):
if (list_s[high] not in vowels):
high -= 1
if (list_s[low] not in vowels):
low += 1
if (list_s[low] in vowels) and (list_s[high] in vowels) :
list_s[high], list_s[low] = list_s[low] , list_s[high]
high -= 1
low += 1
return ''.join(list_s)