美文网首页
[LeetCode][Python]345. Reverse V

[LeetCode][Python]345. Reverse V

作者: bluescorpio | 来源:发表于2017-05-11 22:03 被阅读86次

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".

思路:

设置一个list存放所有的元音字母,共计十个。设置两个游标分别从左右两次计数,不是元音字母,继续向中间移动,如果遇到元音字母,就和另一个方向的元音字母交换。直到游标相遇为止。

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        low, high = 0, len(s)-1
        list_s = list(s)
        while(low < high):
            if (list_s[high] not in vowels):
                high -= 1
            if (list_s[low] not in vowels):
                low += 1
            if (list_s[low] in vowels) and (list_s[high] in vowels) :
                list_s[high], list_s[low] = list_s[low] , list_s[high]
                high -= 1
                low += 1
        return ''.join(list_s)

相关文章

网友评论

      本文标题:[LeetCode][Python]345. Reverse V

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