题目:
Given a string s, reverse only all the vowels in the string and return it.
The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.
给定一个字串,将其里面母音的位置反转
ex:input:"hello"=>output:"holle"
这题跟344.还蛮像的
只是多了些条件判断
class Solution: def reverseVowels(self, s: str) -> str: l=0 r=len(s)-1 s=list(s) while l<r: while l<r and s[l] not in "AEIOUaeiou": l=l+1 while l<r and s[r] not in "AEIOUaeiou": r=r-1 if l<r: s[l],s[r]=s[r],s[l] l=l+1 r=r-1 return "".join(s)
先将字串转为字元阵列方便位置的互换
设立两个指标(l,r),一个从阵列头,一个从阵列尾开始走
两者走到母音的位置停下,透过两者位置决定是否互换值
互换完两者下一轮再继续寻找下一个母音进行交换
不断重複直到两者相遇或交错
之后用join将阵列变回字串回传
最后执行时间51ms(faster than 96.31%)
那我们下题见