Write a function that takes a string as input and reverse only the vowels of a string.git
Example 1:github
Input: "hello"
Output: "holle"
Example 2:函數
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".ui
編寫一個函數,以字符串做爲輸入,反轉該字符串中的元音字母。code
示例 1:索引
輸入: "hello"
輸出: "holle"
示例 2:ip
輸入: "leetcode"
輸出: "leotcede"
說明:
元音字母不包含字母"y"。utf-8
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-04-08 22:07:12 # @Last Modified by: 何睿 # @Last Modified time: 2019-04-08 22:07:12 class Solution: def reverseVowels(self, s: str) -> str: # 全部的元音字母 vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"} index = [i for i in range(len(s)) if s[i] in vowels] half, count = len(index) // 2, len(index) - 1 s = list(s) # 交換全部的緣由字母 for i in range(half): s[index[i]], s[index[count - i]] = s[index[count - i]], s[index[i]] return ''.join(s)