LeetCode 题解工作台

得到 K 个黑块的最少涂色次数

给你一个长度为 n 下标从 0 开始的字符串 blocks , blocks[i] 要么是 'W' 要么是 'B' ,表示第 i 块的颜色。字符 'W' 和 'B' 分别表示白色和黑色。 给你一个整数 k ,表示想要 连续 黑色块的数目。 每一次操作中,你可以选择一个白色块将它 涂成 黑色块。 请你…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们观察发现,题目实际上求的是一个 大小的滑动窗口中白色块的最小数量。 因此,我们只需要遍历字符串 ,用一个变量 统计当前窗口中白色块的数量,然后用一个变量 维护最小值即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 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.length
  • 1 <= n <= 100
  • blocks[i] 要么是 'W' ,要么是 'B'
  • 1 <= k <= n
lightbulb

解题思路

方法一:滑动窗口

我们观察发现,题目实际上求的是一个 kk 大小的滑动窗口中白色块的最小数量。

因此,我们只需要遍历字符串 blocksblocks,用一个变量 cntcnt 统计当前窗口中白色块的数量,然后用一个变量 ansans 维护最小值即可。

遍历结束后即可得到答案。

时间复杂度 O(n)O(n),其中 nn 为字符串 blocksblocks 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

得到 K 个黑块的最少涂色次数题解:滑动窗口(状态滚动更新) | LeetCode #2379 简单