原题是:
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".
思路是:
两个指针分别从头尾去寻找元音,两个找到的时候,就交换。一个是,另一个不是的时候,挪动不是元音的那个指针。
代码是:
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
i = 0
j = len(s) - 1
length = len(s)
strlist = list(s)
vowels = set(['a','e','i','o','u','A','E','I','O','U'])
while(i < j):
if strlist[i] in vowels and strlist[j] in vowels:
tmp = strlist[i]
strlist[i] = strlist[j]
strlist[j] = tmp
i += 1
j -= 1
elif strlist[i] in vowels and strlist[j] not in vowels:
j -= 1
else :
i += 1
return ''.join(strlist)
网友评论