Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Reverse Vowels of a String

$
0
0

题目描述:

LeetCode 345. 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".

题目大意:

编写函数输入一个字符串,将其中的元音字母逆置。

测试用例如题目描述。

解题思路:

双指针法(Two Pointers)

Python代码:

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        VOWELS = ('a', 'e', 'i', 'o', 'u')
        size = len(s)
        left, right = 0, size - 1
        ls = list(s)
        while True:
            while left < size and s[left].lower() not in VOWELS:
                left += 1
            while right >= 0 and s[right].lower() not in VOWELS:
                right -= 1
            if left >= right: break
            ls[left], ls[right] = ls[right], ls[left]
            left, right = left + 1, right - 1
        return ''.join(ls)

精简版Python代码,详见LeetCode Discuss:https://leetcode.com/discuss/99073/1-2-lines-python-ruby

def reverseVowels(self, s):
    vowels = re.findall('(?i)[aeiou]', s)
    return re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)

 


Viewing all articles
Browse latest Browse all 559

Latest Images

Trending Articles



Latest Images