Python [Leetcode 345]Reverse Vowels of a String
题目描述:
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(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = set(list('aeiouAEIOU')) s = list(s) start = 0 end = len(s) - 1 while start <= end: if s[start] in vowels and s[end] in vowels : s[start], s[end] = s[end], s[start] start += 1 end -= 1 else: if s[start] not in vowels: start += 1 if s[end] not in vowels: end -= 1 return ''.join(s)