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

posted @ 2016-12-03 22:29  oO上官麦兜Oo  阅读(184)  评论(0编辑  收藏  举报