首页 > 其他 > 详细

LeetCode #345 Reverse Vowels of a String

时间:2016-12-04 00:25:13      阅读:151      评论:0      收藏:0      [点我收藏+]

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

LeetCode #345 Reverse Vowels of a String

原文:http://www.cnblogs.com/liziran/p/6129850.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!