日野弥生:勉強しよう

LeetCode 345 - 反转字符串中的元音字母

发表于2025年04月12日

#双指针 #字符串

头尾双指针互相逼近即可。

class Solution:
    def reverseVowels(self, s: str) -> str:
        新增函数特殊判断元音
        def isVowel(ch: str) -> bool:
            return ch in "aeiouAEIOU"
        
        # python3字符串不可修改,先搞成list后面再用join转成字符串
        s = list(s)  # 转换为列表,便于修改
        i, j = 0, len(s) - 1
        
        while i < j:
            if not isVowel(s[i]):
                i += 1
            elif not isVowel(s[j]):
                j -= 1
            else:
                # 交换元音字母
                s[i], s[j] = s[j], s[i]
                i += 1
                j -= 1
        
        return "".join(s)  # 转换回字符串并返回

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/reverse-vowels-of-a-string/

上一篇

LeetCode 334 - 递增的三元子序列

下一篇

LeetCode 443 - 压缩字符串