一、问题描述
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 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)
三、运行结果
最后
以上就是标致外套最近收集整理的关于leetcode-345. 反转字符串中的元音字母的全部内容,更多相关leetcode-345.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复