题目描述
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 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)