LeetCode 题解工作台
得到 K 个黑块的最少涂色次数
给你一个长度为 n 下标从 0 开始的字符串 blocks , blocks[i] 要么是 'W' 要么是 'B' ,表示第 i 块的颜色。字符 'W' 和 'B' 分别表示白色和黑色。 给你一个整数 k ,表示想要 连续 黑色块的数目。 每一次操作中,你可以选择一个白色块将它 涂成 黑色块。 请你…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 滑动窗口(状态滚动更新)
答案摘要
我们观察发现,题目实际上求的是一个 大小的滑动窗口中白色块的最小数量。 因此,我们只需要遍历字符串 ,用一个变量 统计当前窗口中白色块的数量,然后用一个变量 维护最小值即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个长度为 n 下标从 0 开始的字符串 blocks ,blocks[i] 要么是 'W' 要么是 'B' ,表示第 i 块的颜色。字符 'W' 和 'B' 分别表示白色和黑色。
给你一个整数 k ,表示想要 连续 黑色块的数目。
每一次操作中,你可以选择一个白色块将它 涂成 黑色块。
请你返回至少出现 一次 连续 k 个黑色块的 最少 操作次数。
示例 1:
输入:blocks = "WBBWWBBWBW", k = 7 输出:3 解释: 一种得到 7 个连续黑色块的方法是把第 0 ,3 和 4 个块涂成黑色。 得到 blocks = "BBBBBBBWBW" 。 可以证明无法用少于 3 次操作得到 7 个连续的黑块。 所以我们返回 3 。
示例 2:
输入:blocks = "WBWBBBW", k = 2 输出:0 解释: 不需要任何操作,因为已经有 2 个连续的黑块。 所以我们返回 0 。
提示:
n == blocks.length1 <= n <= 100blocks[i]要么是'W',要么是'B'。1 <= k <= n
解题思路
方法一:滑动窗口
我们观察发现,题目实际上求的是一个 大小的滑动窗口中白色块的最小数量。
因此,我们只需要遍历字符串 ,用一个变量 统计当前窗口中白色块的数量,然后用一个变量 维护最小值即可。
遍历结束后即可得到答案。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
ans = cnt = blocks[:k].count('W')
for i in range(k, len(blocks)):
cnt += blocks[i] == 'W'
cnt -= blocks[i - k] == 'W'
ans = min(ans, cnt)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidates should be able to recognize that a sliding window approach is optimal for this problem.
- question_mark
Watch for the ability to efficiently update the window state with minimal overhead as the window slides.
- question_mark
Look for candidates who can quickly explain the efficiency of the O(n) time complexity and O(1) space complexity.
常见陷阱
外企场景- error
Not recognizing that the problem can be solved with a sliding window, leading to inefficient brute force approaches.
- error
Failing to update the window's state efficiently as it slides, causing unnecessary recalculations.
- error
Misunderstanding the constraints and not considering that the window must be exactly size k, potentially leading to incorrect results.
进阶变体
外企场景- arrow_right_alt
Consider variations where k is larger or smaller relative to n, or the string is heavily biased toward one color.
- arrow_right_alt
What if the problem asked for at least m consecutive black blocks, where m is variable and provided as an input?
- arrow_right_alt
Instead of counting 'W' blocks, what if the problem required finding the most efficient way to create exactly k consecutive black blocks without exceeding it?