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".
思路:
設置一個list存放所有的元音字母,共計十個。設置兩個游標分別從左右兩次計數,不是元音字母,繼續向中間移動,如果遇到元音字母,就和另一個方向的元音字母交換。直到游標相遇為止。
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)