题目:
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”.
方法一:性能105ms
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
ls = list(s)
vowels = 'aeiouAEIOU'
pos = []
for i in range(len(s)):
if s[i] in vowels:
pos.append((i,s[i]))
if len(pos) < 2:
return s
for i in range(len(pos)/2):
ls[pos[i][0]] = pos[len(pos)-i-1][1]
ls[pos[len(pos)-i-1][0]] = pos[i][1]
return ''.join(ls)
方法二:性能68ms
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = set(list('aeiouAEIOU'))
s = list(s)
front = 0
end = len(s)-1
while front < end:
if s[front] in vowels:
while not s[end] in vowels and front < end:
end -= 1
s[front], s[end] = s[end], s[front]
end -= 1
front += 1
return ''.join(s)