【LeetCode】Python实现-345. 反转字符串中的元音字母
2019-03-21 20:59
351 查看
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
示例 1:
输入: “hello”
输出: “holle”
示例 2:
输入: “leetcode”
输出: “leotcede”
说明:
元音字母不包含字母"y"。
我的解答:
先将字符串中的所有元音字母取出来,然后进行反转,再依次在原来元音字母的位置插入进去。
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ n = 'aeiouAEIOU' m = j = '' c = 0 for i in range(len(s)): if s[i] in n: m += s[i] k = m[::-1] for i in range(len(s)): if s[i] in n: j += k[c] c += 1 else: j += s[i] return j
别人的解答:
先将字符串转化为列表,然后从首尾两端同时开始向中间遍历,判断是否是元音字母,是的话就交换两个字母的位置,最后再利用join方法将列表转换为字符串。
这种方法效率更高,只需一次遍历就可完成任务,而我的算法则需要遍历两次。
y = {'a','e','i','o','u','A','E','I','O','U'} lis = list(s) l = len(lis) i = 0 j = l - 1 while True: while i < l and lis[i] not in y: i += 1 while j >= 0 and lis[j] not in y: j -= 1 #print(i, j) if i >= j: break lis[i], lis[j] = lis[j], lis[i] i += 1 j -= 1 return ''.join(lis)
相关文章推荐
- LeetCode 345. 反转字符串中的元音字母 Python
- leetcode 345.反转字符串中的元音字母
- LeetCode344.python实现: 反转字符串问题☆
- [leetcode]反转字符串中的元音字母[javascript]
- LeetCode557.python实现: 反转字符串中的单词 III问题☆
- [LeetCode] Reverse Vowels of a String 翻转字符串中的元音字母
- [Leetcode,python] Reverse String 反转字符串
- Leetcode反转元音字母
- Python字符串处理实现单词反转
- python 元音字母反转
- [leetcode, python] Reverse Words in a String 反转字符串
- Python实现字符串反转的常用方法分析【4种方法】
- leetcode 反转字符串 (C++实现)
- [Leetcode,python] Reverse String 反转字符串
- [Leetcode,python] Reverse String 反转字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- Python 实现字符串反转的四种方法
- 字符串元音字母反转,其他的不变
- LeetCode 541. 反转字符串 II Python
- leetcode 345 Reverse Vowels of a String(翻转字符串中的元音字母)