leetcode345

原创 2016年06月01日 13:49:19

easy,345
*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”.*
自己是这样写的:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        blist=[]
        for str in s:
            if str in ['a','e','i','o','u','A','E','I','O','U']:
                blist.append(str)
        blist.reverse()
        num=0
        alist=list(s)
        for j in range(len(alist)):
            if alist[j] in ['a','e','i','o','u','A','E','I','O','U']:
                alist[j]=blist[num]
                num=num+1
        news=''.join(alist)
        return news

在Discuss上看到一个想法很好的:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vovels=[]
        index=[]
        l=list(s)
        for i in range(len(l)):
                if l[i] in 'aeiouAEIOU':
                    index.append(i)
                    vovels.append(l[i])
        for i in index:
            l[i] = vovels.pop()
        return ''.join(l)
 *这种方法巧妙在:将元音的索引保存在一个数组中,这样就不用像我的方法一样,当要换元素时还要再遍历一遍,还有比较巧妙的事pop()正好是从最后一位开始的 这样就实现的逆序。*          
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 345. Reverse Vowels of a String

345. Reverse Vowels of a StringWrite a function that takes a string as input and reverse only the vo...

LeetCode 345 Reverse Vowels of a String (in java)

Write a function that takes a string as input and reverse only the vowels of a string. Example ...

LeetCode - 345. Reverse Vowels of a String

和前面Reverse String的思想是一样的,同样是需要维护两个指针,一个在开头,一个在结尾,如果遇到元音字母就互相交换它们。注意这里判断原因字母的方法,使用了一个String vowel:  "...

LeetCode笔记:345. Reverse Vowels of a String

翻转字符串中所有元音的位置

[LeetCode-345]Reverse Vowels of a String(java)

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: ...

[LeetCode]344. Reverse String&345. Reverse Vowels of a String&151. Reverse Words in a String

344. Reverse String 345. Reverse Vowels of a String 151. Reverse Words in a String

Leetcode #345. Reverse Vowels of a String 逆转元音字母 解题报告

1 解题思想这道题是逆转字符串的一个变种,要求的只是把元音的部分进行逆转,非元音的地方不进行逆转。所以基本的思想就是: 1、单独的扫描一次元音,得道其序列(我们可以逆序扫描,这样读出的时候直接就是逆...
  • MebiuW
  • MebiuW
  • 2016年05月02日 13:41
  • 592

LeetCode 345. Reverse Vowels of a String 解题报告

LeetCode 345. Reverse Vowels of a String 解题报告

<LeetCode OJ> 345 / 344 Reverse Vowels of a String / Reverse String

Total Accepted: 537 Total Submissions: 1488 Difficulty: Easy Write a function that takes a stri...

【leetcode】345. Reverse Vowels of a String

一、题目描述 Write a function that takes a string as input and reverse only the vowels of a string. Exa...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode345
举报原因:
原因补充:

(最多只允许输入30个字)