LeetCode 题解工作台
字符串元音游戏
小红和小明在玩一个字符串元音游戏。 给你一个字符串 s ,小红和小明将轮流参与游戏,小红 先 开始: 在小红的回合,她必须移除 s 中包含 奇数 个元音的任意 非空 子字符串 。 在小明的回合,他必须移除 s 中包含 偶数 个元音的任意 非空 子字符串 。 第一个无法在其回合内进行移除操作的玩家输掉…
4
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数学·string
答案摘要
我们不妨记字符串中元音字母的个数为 。 如果 $k = 0$,即字符串中没有元音字母,那么小红无法移除任何子字符串,小明直接获胜。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
小红和小明在玩一个字符串元音游戏。
给你一个字符串 s,小红和小明将轮流参与游戏,小红 先 开始:
- 在小红的回合,她必须移除
s中包含 奇数 个元音的任意 非空 子字符串。 - 在小明的回合,他必须移除
s中包含 偶数 个元音的任意 非空 子字符串。
第一个无法在其回合内进行移除操作的玩家输掉游戏。假设小红和小明都采取 最优策略 。
如果小红赢得游戏,返回 true,否则返回 false。
英文元音字母包括:a, e, i, o, 和 u。
示例 1:
输入: s = "leetcoder"
输出: true
解释:
小红可以执行如下移除操作来赢得游戏:
- 小红先手,她可以移除加下划线的子字符串
s = "leetcoder",其中包含 3 个元音。结果字符串为s = "der"。 - 小明接着,他可以移除加下划线的子字符串
s = "der",其中包含 0 个元音。结果字符串为s = "er"。 - 小红再次操作,她可以移除整个字符串
s = "er",其中包含 1 个元音。 - 又轮到小明,由于字符串为空,无法执行移除操作,因此小红赢得游戏。
示例 2:
输入: s = "bbcd"
输出: false
解释:
小红在她的第一回合无法执行移除操作,因此小红输掉了游戏。
提示:
1 <= s.length <= 105s仅由小写英文字母组成。
解题思路
方法一:脑筋急转弯
我们不妨记字符串中元音字母的个数为 。
如果 ,即字符串中没有元音字母,那么小红无法移除任何子字符串,小明直接获胜。
如果 为奇数,那么小红可以移除整个字符串,小红直接获胜。
如果 为偶数,那么小红可以移除 个元音字母,此时剩下一个元音字母,小明无法移除任何子字符串,小红直接获胜。
综上所述,如果字符串中包含元音字母,那么小红获胜,否则小明获胜。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def doesAliceWin(self, s: str) -> bool:
vowels = set("aeiou")
return any(c in vowels for c in s)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on traversing the string once to count vowels, giving O(n). Space complexity is O(1) since only counters are needed. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate identifies counting vowels as the key first step.
- question_mark
Observe if the candidate considers the failure mode when the string has no vowels.
- question_mark
Look for recognition that optimal play can be predicted using simple math rather than full simulation.
常见陷阱
外企场景- error
Failing to check if the initial string has zero vowels, leading to incorrect winner prediction.
- error
Overcomplicating the game simulation instead of using vowel count and turn logic.
- error
Ignoring edge cases with single-character strings or strings with all consonants.
进阶变体
外企场景- arrow_right_alt
Change the winning condition to removing consonants instead of vowels and analyze the impact on optimal strategy.
- arrow_right_alt
Use a string with alternating vowels and consonants to see how move sequences affect the winner.
- arrow_right_alt
Introduce a rule limiting moves per turn to 2 vowels, requiring adjusted math for optimal play.