码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #345 Reverse Vowels of a String

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

标签:targe   etc   log   else   否则   ret   example   ring   function   

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

标签:targe   etc   log   else   否则   ret   example   ring   function   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!