1. 程式人生 > >LeetCode刷題記錄——第345題(反轉字串中母音字母)

LeetCode刷題記錄——第345題(反轉字串中母音字母)

題目描述

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

示例 1:

輸入: “hello”
輸出: “holle”

示例 2:

輸入: “leetcode”
輸出: “leotcede”

思路分析

  • 將所有母音字母放在一個列表裡,方便後續用if語句判定s中的元素是否在母音列表中
  • str轉換為list,方便用索引交換字母
  • 利用while迴圈,判定標準是front<end,迴圈體內包含的程式碼是,判定是否母音和交換程式碼
    • front從前,end從後。如果front所在元素是母音,則end從後往前一直找,找到第一個母音,並交換
    • front往後移動一位,判定是否是母音(是否在vowels這個list中)

程式碼示例

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowels = list("aeiouAEIOU")
        s = list(s)
        front = 0
        end = len(s) - 1
        while front <
end: if s[front] in vowels: while s[end] not in vowels: end -= 1 s[front],s[end] = s[end],s[front] end -= 1 front += 1 return "".join(s)