LeetCode 345. Reverse Vowels of a String

Description

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

思路

  • 這道題和上一道題目 344 Reverse String 作法基本同樣,只是這裏只須要交換緣由字母。
  • 找到全部的元音字母索引,第一個索引對應的元素和最後一個索引對應的元素交換,第二個和倒數第二個交換,第三個和倒數第三個交換。
# -*- 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)

源代碼文件在 這裏
©本文首發於 何睿的博客 ,歡迎轉載,轉載需保留 文章來源 ,做者信息和本聲明.leetcode

相關文章
相關標籤/搜索