[LeetCode][Python]345. Reverse Vowels of a String

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)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容