leetcode with python:345. Reverse Vowels of a String

题目:

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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章