美文网首页
[easy][String][Two-pointers]345.

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

作者: 小双2510 | 来源:发表于2017-11-25 23:27 被阅读0次

原题是:

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)

相关文章

网友评论

      本文标题:[easy][String][Two-pointers]345.

      本文链接:https://www.haomeiwen.com/subject/phrhbxtx.html