LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

345. 反转字符串中的元音字母

给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。

元音字母包括 'a''e''i''o''u',且可能以大小写两种形式出现。

示例 1:

输入:s = "hello"
输出:"holle"

示例 2:

输入:s = "leetcode"
输出:"leotcede"

提示:

双指针 简单

代码

class Solution:
    def reverseVowels(self, s: str) -> str:
        s = list(s)
        vowel = {'a','e','i','o','u','A','E','I','O','U'}
        lp, rp= 0, len(s)-1
        while lp < rp:
            if s[lp] in vowel and s[rp] in vowel:
                s[lp], s[rp] =  s[rp], s[lp]
                lp += 1
                rp -= 1
                continue
            if s[lp] not in vowel:
                lp += 1
            if s[rp] not in vowel:
                rp -= 1
        return ''.join(s)