[easy][String][Two-pointers]345.Reverse vowels

原题是:

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:
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        
        i = 0 
        j = len(s) - 1
        length = len(s)
        strlist = list(s)
        vowels = set(['a','e','i','o','u','A','E','I','O','U'])
        while(i < j):
            if strlist[i] in vowels and strlist[j] in vowels:
                tmp = strlist[i]
                strlist[i] = strlist[j]
                strlist[j] = tmp
                i += 1
                j -= 1
            elif strlist[i] in vowels and strlist[j] not in vowels:
                j -= 1
            else :
                i += 1
        return ''.join(strlist)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容