LeetCode #345 Reverse Vowels of a String

本文提供了一种高效的方法来反转字符串中的元音字母,通过使用双指针技巧,仅在遇到元音时进行交换,有效降低了时间复杂度。

https://leetcode.com/problems/reverse-vowels-of-a-string/

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:
The vowels does not include the letter "y".

 

维护首尾两个指针i和j,每次循环如果s[i]和s[j]都是vowel才交换,否则哪个不是vowel,就让i++或j--,直到i==j遍历完毕,时间复杂度O(N)

需要注意的是python中str是不能直接内部互换元素的,所以需要先转换成list,最后再join到一个空串返回

class Solution(object):
    def reverseVowels(self, s):
        res = list(s)
        vowels = ['a', 'e', 'i', 'o', 'u']
        i = 0; j = len(s) - 1
        while i < j:
            if res[i].lower() not in vowels:
                i += 1
            elif res[j].lower() not in vowels:       
                j -= 1
            else:
                res[i],res[j] = res[j],res[i]
                i += 1
                j -= 1
        return "".join(res)

检查是否是vowel可以先创建vowel的list,再看是否in即可,不用再另外定义一个函数判断vowel

转载于:https://www.cnblogs.com/liziran/p/6129850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值