问题描述:
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello" 输出: "holle"
示例 2:
输入: "leetcode" 输出: "leotcede"
说明:
元音字母不包含字母"y"。
方法: 用一个list纪录元音字母的索引 index = [],对里面的value进行swap.
1 class Solution(object): 2 def reverseVowels(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 pattern = "aeiouAEIOU" 8 index = [] 9 strToList = list(s) 10 for i in range(len(s)): 11 if strToList[i] in pattern: 12 index.append(i) 13 j = len(index) 14 for i in range(j // 2): 15 strToList[index[i]],strToList[index[j - i - 1]] = strToList[index[j - i - 1]],strToList[index[i]]#交换 16 s = "" 17 for i in strToList: 18 s += i 19 return s
官方:
1 class Solution(object): 2 def reverseVowels(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 s = list(s) 8 l = len(s) 9 10 yun = set(('a', 'e', 'i', 'o', 'u','A', 'E', 'I', 'O', 'U')) 11 12 i = 0 13 j = l-1 14 15 while i < j: 16 while i < j: 17 if s[i] in yun: 18 break 19 i += 1 20 21 while i < j: 22 if s[j] in yun: 23 break 24 j -= 1 25 26 s[i], s[j] = s[j], s[i] 27 i += 1 28 j -= 1 29 30 return "".join(s)
2018-09-26 14:46:24