LeetCode 题解工作台

反转字符串中的元音字母

给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。 元音字母包括 'a' 、 'e' 、 'i' 、 'o' 、 'u' ,且可能以大小写两种形式出现不止一次。 示例 1: 输入: s = "IceCreAm" 输出: "AceCreIm" 解释: s 中的元音是 ['I', '…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们可以用两个指针 和 ,初始时分别指向字符串的首尾。 每次循环判断 指向的字符是否是元音字母,如果不是则向后移动 ;同理,判断 指向的字符是否是元音字母,如果不是则向前移动 。如果此时 $i \lt j$,那么 和 指向的字符都是元音字母,交换这两个字符。然后向后移动 ,向前移动 。继续上述操作,直到 $i \ge j$。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

 

示例 1:

输入:s = "IceCreAm"

输出:"AceCreIm"

解释:

s 中的元音是 ['I', 'e', 'e', 'A']。反转这些元音,s 变为 "AceCreIm".

示例 2:

输入:s = "leetcode"

输出:"leotcede"

 

提示:

  • 1 <= s.length <= 3 * 105
  • s可打印的 ASCII 字符组成
lightbulb

解题思路

方法一:双指针

我们可以用两个指针 iijj,初始时分别指向字符串的首尾。

每次循环判断 ii 指向的字符是否是元音字母,如果不是则向后移动 ii;同理,判断 jj 指向的字符是否是元音字母,如果不是则向前移动 jj。如果此时 i<ji \lt j,那么 iijj 指向的字符都是元音字母,交换这两个字符。然后向后移动 ii,向前移动 jj。继续上述操作,直到 iji \ge j

时间复杂度 O(n)O(n),其中 nn 是字符串的长度。空间复杂度 O(Σ)O(|\Sigma|),其中 Σ\Sigma 是字符集的大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = "aeiouAEIOU"
        i, j = 0, len(s) - 1
        cs = list(s)
        while i < j:
            while i < j and cs[i] not in vowels:
                i += 1
            while i < j and cs[j] not in vowels:
                j -= 1
            if i < j:
                cs[i], cs[j] = cs[j], cs[i]
                i, j = i + 1, j - 1
        return "".join(cs)
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for proficiency with the two-pointer technique and how candidates manage pointer movement.

  • question_mark

    Ensure the candidate accounts for both uppercase and lowercase vowels during swaps.

  • question_mark

    Assess the candidate's ability to optimize for space complexity, especially when handling large input sizes.

warning

常见陷阱

外企场景
  • error

    Failing to skip non-vowel characters efficiently can lead to unnecessary checks and inefficiency.

  • error

    Not handling both uppercase and lowercase vowels correctly might result in incorrect outputs.

  • error

    Attempting to reverse vowels without properly converting the string to a mutable data structure could cause errors in languages where strings are immutable.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Reverse the vowels only in a substring, not the entire string.

  • arrow_right_alt

    Add a limit to the number of vowels that can be reversed, such as reversing only the first 3 vowels.

  • arrow_right_alt

    Consider a case where only specific vowels (e.g., 'a' and 'o') are reversed, not all vowels.

help

常见问题

外企场景

反转字符串中的元音字母题解:双·指针·invariant | LeetCode #345 简单