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

思路:

設(shè)置一個(gè)list存放所有的元音字母,共計(jì)十個(gè)。設(shè)置兩個(gè)游標(biāo)分別從左右兩次計(jì)數(shù),不是元音字母,繼續(xù)向中間移動(dòng),如果遇到元音字母,就和另一個(gè)方向的元音字母交換。直到游標(biāo)相遇為止。

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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,837評(píng)論 18 139
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,766評(píng)論 0 33
  • Description Write a function that takes a string as input...
    去留無意hmy閱讀 638評(píng)論 0 0
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,786評(píng)論 0 23
  • 最近在看一本小說,今天看到內(nèi)容是一個(gè)孩子。一個(gè)小男孩,挺調(diào)皮搗蛋的。不怕他的父母,很尊重他們。里面有個(gè)場(chǎng)景是他家領(lǐng)...
    南安有淮水閱讀 219評(píng)論 0 0