【LeetCode 简单题】78-反转字符串中的元音字母

声明:

今天是第78道题。编写一个函数,以字符串作为输入,反转该字符串中的元音字母。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

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

示例 1:

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

示例 2:

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

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

解法1。用对撞指针的思想,一左一右,如果指向的当前元素不是元音字母,就跳过,反之两者交换后继续遍历。

执行用时: 156 ms, 在Reverse Vowels of a String的Python提交中击败了47.32% 的用户

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = 0
        r = len(s)-1
        s = list(s)
        vowel = ['a','e','i','o','u','A','E','I','O','U']
        while l < r:
            if s[l] not in vowel:
                l += 1
                continue
            if s[r] not in vowel:
                r += 1
                continue
            s[l],s[r] = s[r],s[l]
            l += 1
            r -= 1    # 注意这里是减号,别顺手写错了
        return ''.join(s)

 解法2。更加pythonic的简洁代码,用一个stack存储s中出现过的元音字母,然后在返回结果时如果是元音就用stack的最后一个元素代替,代码如下。

执行用时: 288 ms, 在Reverse Vowels of a String的Python提交中击败了8.17% 的用户

class Solution(object):
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowel = ['a','e','i','o','u','A','E','I','O','U']
        stack = [i for i in s if i in vowel]
        return ''.join([i if i not in vowel else stack.pop() for i in s])

结尾

解法1&解法2:https://blog.csdn.net/qq_17550379/article/details/80515302

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83831874
今日推荐