LeetCode 题解工作台
如果相邻两个颜色均相同则删除当前颜色
总共有 n 个颜色片段排成一列,每个颜色片段要么是 'A' 要么是 'B' 。给你一个长度为 n 的字符串 colors ,其中 colors[i] 表示第 i 个颜色片段的颜色。 Alice 和 Bob 在玩一个游戏,他们 轮流 从这个字符串中删除颜色。Alice 先手 。 如果一个颜色片段为 '…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们统计字符串 `colors` 中连续出现 个 `'A'` 或 个 `'B'` 的个数,分别记为 和 。 最后判断 是否大于 ,是则返回 `true`,否则返回 `false`。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
总共有 n 个颜色片段排成一列,每个颜色片段要么是 'A' 要么是 'B' 。给你一个长度为 n 的字符串 colors ,其中 colors[i] 表示第 i 个颜色片段的颜色。
Alice 和 Bob 在玩一个游戏,他们 轮流 从这个字符串中删除颜色。Alice 先手 。
- 如果一个颜色片段为
'A'且 相邻两个颜色 都是颜色'A',那么 Alice 可以删除该颜色片段。Alice 不可以 删除任何颜色'B'片段。 - 如果一个颜色片段为
'B'且 相邻两个颜色 都是颜色'B',那么 Bob 可以删除该颜色片段。Bob 不可以 删除任何颜色'A'片段。 - Alice 和 Bob 不能 从字符串两端删除颜色片段。
- 如果其中一人无法继续操作,则该玩家 输 掉游戏且另一玩家 获胜 。
假设 Alice 和 Bob 都采用最优策略,如果 Alice 获胜,请返回 true,否则 Bob 获胜,返回 false。
示例 1:
输入:colors = "AAABABB" 输出:true 解释: AAABABB -> AABABB Alice 先操作。 她删除从左数第二个 'A' ,这也是唯一一个相邻颜色片段都是 'A' 的 'A' 。 现在轮到 Bob 操作。 Bob 无法执行任何操作,因为没有相邻位置都是 'B' 的颜色片段 'B' 。 因此,Alice 获胜,返回 true 。
示例 2:
输入:colors = "AA" 输出:false 解释: Alice 先操作。 只有 2 个 'A' 且它们都在字符串的两端,所以她无法执行任何操作。 因此,Bob 获胜,返回 false 。
示例 3:
输入:colors = "ABBBBBBBAAA" 输出:false 解释: ABBBBBBBAAA -> ABBBBBBBAA Alice 先操作。 她唯一的选择是删除从右数起第二个 'A' 。 ABBBBBBBAA -> ABBBBBBAA 接下来轮到 Bob 操作。 他有许多选择,他可以选择任何一个 'B' 删除。 然后轮到 Alice 操作,她无法删除任何片段。 所以 Bob 获胜,返回 false 。
提示:
1 <= colors.length <= 105colors只包含字母'A'和'B'
解题思路
方法一:计数
我们统计字符串 colors 中连续出现 个 'A' 或 个 'B' 的个数,分别记为 和 。
最后判断 是否大于 ,是则返回 true,否则返回 false。
时间复杂度 ,其中 为字符串 colors 的长度。空间复杂度 。
class Solution:
def winnerOfGame(self, colors: str) -> bool:
a = b = 0
for c, v in groupby(colors):
m = len(list(v)) - 2
if m > 0 and c == 'A':
a += m
elif m > 0 and c == 'B':
b += m
return a > b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for efficient ways to simulate the turn-based nature of the game.
- question_mark
The candidate should demonstrate an understanding of greedy algorithms and their application to this problem.
- question_mark
Consider how optimizations can reduce the time complexity for large input sizes.
常见陷阱
外企场景- error
Misunderstanding the game mechanics can lead to incorrect simulations or missed moves.
- error
Failing to optimize the search for valid moves can result in inefficient solutions for large inputs.
- error
Not correctly handling the alternating nature of the game can lead to errors in turn simulation.
进阶变体
外企场景- arrow_right_alt
What if the number of valid moves changes dynamically due to prior removals?
- arrow_right_alt
How would the solution change if players could remove pieces that have neighbors of different colors?
- arrow_right_alt
What if players could remove any piece that is a neighbor to a matching color, not just surrounded pieces?