【004】Leetcode—雙重指針—345. 反轉字符串中的元音字母(Reverse Vowels of a String)

題目信息

編寫一個函數,以字符串作爲輸入,反轉該字符串中的元音字母。

說明:

  • 返回的下標值(index1 和 index2)不是從零開始的。
  • 你可以假設每個輸入只對應唯一的答案,而且你不可以重複使用相同的元素。

示例:

1:

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

2:

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

解題思路

		number = ['a','e','i','o','u','A','E','I','O','U']
        res = list(s)
        result = []
        index = 0

        #倒序打印元音字母 利用迭代器
        b = [x for x in reversed(res) if x in number]
        #print(b)

        #遍歷修改
        for item in res:
            if item not in number:
                result.append(item)
            else:
                result.append(b[index])
                index += 1

        return ''.join(result)

主要思路是將單詞中的元音字母提取出來,然後反轉,再遍歷原單詞按條件塞入result中,注意輸入輸出都是string類型,需要一定的轉換。

學習

TODO

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章