反轉字串中的母音字母

2022-08-31 10:03:08 字數 965 閱讀 3780

1. 題目描述

給乙個字串,將字串中前後對應的母音字母進行反轉,即左邊一半的母音字母與右邊一半母音字母映象反轉

example 1:

input: "hello"

output: "holle"

example 2:

input: "leetcode"

output: "le

otcede"

2. 解題**

class solution:

def reversevowels(self, s: str) -> str:

vowels = ['a','e','i','o','u','a','e','i','o','u']

lens = len(s)

i = 0

j = lens-1

list_s = list(s)

while i < j : #保證左邊索引不超過右邊

if list_s[i] not in vowels : #判斷左邊的母音字元,如果對應位置的字元不是母音字母,則索引加一

i += 1

#continue

if list_s[j] not in vowels : #判斷右邊的母音字元,如果對應位置的字元不是母音字母,則索引減一

j -= 1

#continue

if list_s[i] in vowels and list_s[j] in vowels : #判斷當次迴圈下索引i, j對應的字元是否同時是母音字母,如果是,則交換位置

list_s[i], list_s[j]= list_s[j], list_s[i]

i += 1

j -= 1

return "".join(list_s) #將字串的列表轉換為字串返回

反轉字串中的母音字母

編寫乙個函式,以字串作為輸入,反轉該字串中的母音字母。示例 1 輸入 hello 輸出 holle 示例 2 輸入 leetcode 輸出 leotcede int vowel char w return flag char reversevowels char s if vowel s j ret...

345 反轉字串中的母音字母

今天分享的是反轉字串中的母音字母,原題目要求如下 編寫乙個函式,以字串作為輸入,反轉該字串中的母音字母。示例 1 輸入 hello 輸出 holle 示例 2 輸入 leetcode 輸出 leotcede 說明 母音字母不包含字母 y 補充說明 母音字母為a o e i u a o e i u 首...

345 反轉字串中的母音字母

編寫乙個函式,以字串作為輸入,反轉該字串中的母音字母。示例 1 輸入 hello 輸出 holle 示例 2 輸入 leetcode 輸出 leotcede 說明 母音字母不包含字母 y 棧 class solution stringbuffer buffer newstringbuffer s f...