Leetcode 345

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:

输入: "hello"
输出: "holle"

示例 2:

输入: "leetcode"
输出: "leotcede"

说明:
元音字母不包含字母"y"。

方法一:传统的思维方式,效率可以接受

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = list(s)
        n = len(s)
        vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        j = 0
        index = []
        for i in range(n):
               if s[i] in vowel:
                    index.append(i)

        length = len(index) - 1
        while j <= (length) and length-j >= j:
            s[index[j]], s[index[length-j]] = s[index[length-j]], s[index[j]]
            j += 1
        return "".join(s)

方法二:类似双指针的方式进行循环

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        s = list(s)
        n = len(s)
        vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        left = 0
        right = n - 1

        while left < right:
            while left < n and s[left] not in vowel:
                left += 1
            while right > 0 and s[right] not in vowel:
                right -= 1
            if left < right:
                s[left], s[right] = s[right], s[left]
                left += 1
                right -= 1
        return ''.join(s)

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/84404852
345