345. Reverse Vowels of a String

problem

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".
  • 题目差点没看懂,大致是要翻转元音字母(百度了下元音字母包含a,e,i,o,u),并且是对称翻转,'leetcode'中第一个‘e’和‘d’不能翻转

如果两边都是元音字母交换,如果某一边不是,向中间移动,直到结束

  • 不得不吐槽下,这个题目和example2加一起,这是让人找规律猜题目么
  • 大小写不区分

solution

  • python 里面使用and时,先计算前面的,如果为False,则后面的不计算
class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = list(s)
        i = 0
        j = len(s)-1
        while i<j:
            if self.vowel(s[i]) and self.vowel(s[j]):
                s[i],s[j] = s[j],s[i]
                i += 1
                j -= 1
            if not self.vowel(s[i]):
                i += 1
            if not self.vowel(s[j]):
                j -= 1
        return ''.join(s)
    
    def vowel(self, char):
        char = char.upper()
        if char in 'AEIOU':
            return True
        else:
            return False
            
  • 上面的解法不难理解,discuss的解法中re.sub比较难理解是怎么用的

re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s) 就是对s里面每个符合条件的执行lambad表达式; 不过很精巧(对符合条件的元素正序进行替换,替换对象采用倒序,完成了倒转)
具体解释放在正则部分吧:http://www.cnblogs.com/salmd/p/5940425.html

def reverseVowels(self, s):
    vowels = re.findall('(?i)[aeiou]', s)
    return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)
posted @ 2016-10-08 21:47  Salmd  阅读(111)  评论(0)    收藏  举报