反转字符串中的元音字母(python3)
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: "hello"
输出: "holle"
示例 2:
输入: "leetcode"
输出: "leotcede"
说明:
元音字母不包含字母"y"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string
代码实现:(可正确执行),推荐
1 class Solution(object): 2 def reverseVowels(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 # strlist = [] 8 word = {'a','e','i','o','u','A','E','I','O','U'} 9 i =0 10 j=len(s)-1 11 s = list(s) 12 13 while i<j: 14 if s[i] not in word: 15 i +=1 16 elif s[j] not in word: 17 j -=1 18 else: 19 s[i],s[j]=s[j],s[i] 20 i +=1 21 j -=1 22 23 return ''.join(s) #将列表转换成字符串
代码实现:(单个字符串适用,有空格的sentence不适用)
解题思路:总体思路和上段代码相似,唯一不同的是字符串s的读取方式,此处将遍历字符串s,读取到列表strlist中,,所以会造成如果s中即使存在空格,也会被当作一个字符读入。
依旧推荐方法1的写法,s=list(s)
1 class Solution(object): 2 def reverseVowels(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 strlist = [] 8 word = ['a','e','i','o','u','A','E','I','O','U'] 9 10 for n in s: 11 strlist.append(n) 12 13 i =0 14 j =len(strlist)-1 15 16 17 while i<j: 18 if strlist[i] not in word: 19 i +=1 20 if strlist[j] not in word: 21 j -=1 22 else: 23 strlist[i],strlist[j]=strlist[j],strlist[i] 24 i +=1 25 j -=1 26 return ''.join(strlist) #将列表转换成字符串 27 28
注意事项:
1. 将word列表变成字典,内存消耗相同,但是字典的执行时间会短很多(结果如下展示)