Leetcode刷题笔记python---反转字符串中的元音字母

反转字符串中的元音字母

题目

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:

输入: “hello”
输出: “holle”
示例 2:

输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。


解答

思路:

  1. 找到字符串中元音字母——循环1
  2. 在找一次——替换,循环2
  3. 把list换成str——循环3

代码:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        voe=['a','e','i','o','u','A','E','I','O','U']
        s=list(s)
        res=[]
        for i in s:
            if i in voe:
                res.append(i)
        n=len(s)
        for i in range(n):
            if s[i] in voe:
                s[i]=res.pop()
        ss=''
        for i in s:
            ss+=i
        return ss

结果:2%
很差!!!
循环用的太多了

ss=’’.join(s)
结果:15%

你可能感兴趣的:(Leetcode刷题笔记python---反转字符串中的元音字母)