本文共 1165 字,大约阅读时间需要 3 分钟。
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"Output: "holle"
Example 2:
Input: "leetcode"Output: "leotcede"
Note:
The vowels does not include the letter "y".思路:建立两个列表,一个是存储遇到的元音字母,一个存储的是元音字母的位置。然后把位置列表倒置,再把元音字母按新的顺序(倒置后的顺序)替换原字符串中的字母。
中间用到了几个方法:set(字符串)可以将字符串存储为单个不重复字母。(用{}存储,不是很理解)
因为字符串不能进行字母替换,所以用list()转为列表,在用join()转为字符串
class Solution: def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = set('aeiouAEIOU') v=[] l=[] for i,char in enumerate(s): if char in vowels: v.append(char) l.append(i) slist=list(s) l.reverse() for i in range(len(l)): slist[l[i]] = v[i] return ''.join(slist)
也看到大佬用re.sub(),re.findall()方法做,不过这里用到了正则模式字符串,不是很懂。记录一下以后学习。
def reverseVowels(self, s): vowels = re.findall('(?i)[aeiou]', s) return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)
def reverseVowels(self, s): vowels = (c for c in reversed(s) if c in 'aeiouAEIOU') return re.sub('(?i)[aeiou]', lambda m: next(vowels), s)
转载地址:http://yprbb.baihongyu.com/