1. 程式人生 > >【LeetCode 簡單題】78-反轉字串中的母音字母

【LeetCode 簡單題】78-反轉字串中的母音字母

宣告:

今天是第78道題。編寫一個函式,以字串作為輸入,反轉該字串中的母音字母。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除

(手動比心ღ( ´・ᴗ・` ))

正文

題目:編寫一個函式,以字串作為輸入,反轉該字串中的母音字母。

示例 1:

輸入: "hello"
輸出: "holle"

示例 2:

輸入: "leetcode"
輸出: "leotcede"

說明: 母音字母不包含字母"y"。

解法1。用對撞指標的思想,一左一右,如果指向的當前元素不是母音字母,就跳過,反之兩者交換後繼續遍歷。

執行用時: 156 ms, 在Reverse Vowels of a String的Python提交中擊敗了47.32% 的使用者

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = 0
        r = len(s)-1
        s = list(s)
        vowel = ['a','e','i','o','u','A','E','I','O','U']
        while l < r:
            if s[l] not in vowel:
                l += 1
                continue
            if s[r] not in vowel:
                r += 1
                continue
            s[l],s[r] = s[r],s[l]
            l += 1
            r -= 1    # 注意這裡是減號,別順手寫錯了
        return ''.join(s)

 解法2。更加pythonic的簡潔程式碼,用一個stack儲存s中出現過的母音字母,然後在返回結果時如果是母音就用stack的最後一個元素代替,程式碼如下。

執行用時: 288 ms, 在Reverse Vowels of a String的Python提交中擊敗了8.17% 的使用者

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowel = ['a','e','i','o','u','A','E','I','O','U']
        stack = [i for i in s if i in vowel]
        return ''.join([i if i not in vowel else stack.pop() for i in s])

結尾