leetcode-345. 反转字符串中的元音字母
一、问题描述
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
给定 s = "hello", 返回 "holle".
示例 2:
给定 s = "leetcode", 返回 "leotcede".
注意:
元音字母不包括 "y".
二、代码和思路
1.分别设置两个标记位i,j分别从0和n-1开始,碰到元音字母则停止向后和向前前进
2.判断i是否小于j,小于的话则交换元音字母
3.最后返回交换后的list的字符串
class Solution(object):
def reverseVowels(self, s):"""
:type s: str
:rtype: str
"""
vowels = 'aeiouAEIOU'
n=len(s)
i,j=0,n-1
s_lst=list(s)
while i<j:
while s_lst[i] not in vowels and i<n-1:
i += 1
while s_lst[j] not in vowels and j>0:
j -= 1
if i<j:
s_lst[i],s_lst[j]=s_lst[j],s_lst[i]
i += 1
j -= 1
return ''.join(s_lst)
三、运行结果