[LeetCode] 2379. Minimum Recolors to Get K Consecutive Black Blocks

You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black, respectively.

You are also given an integer k, which is the desired number of consecutive black blocks.

In one operation, you can recolor a white block such that it becomes a black block.

Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.

Example 1:

Input: blocks = "WBBWWBBWBW", k = 7
Output: 3
Explanation:
One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks
so that blocks = "BBBBBBBWBW". 
It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.
Therefore, we return 3.

Example 2:

Input: blocks = "WBWBBBW", k = 2
Output: 0
Explanation:
No changes need to be made, since 2 consecutive black blocks already exist.
Therefore, we return 0.

Constraints:

  • n == blocks.length
  • 1 <= n <= 100
  • blocks[i] is either 'W' or 'B'.
  • 1 <= k <= n

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

给你一个长度为 n 下标从 0 开始的字符串 blocks ,blocks[i] 要么是 'W' 要么是 'B' ,表示第 i 块的颜色。字符 'W' 和 'B' 分别表示白色和黑色。

给你一个整数 k ,表示想要 连续 黑色块的数目。

每一次操作中,你可以选择一个白色块将它 涂成 黑色块。

请你返回至少出现 一次 连续 k 个黑色块的 最少 操作次数。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-recolors-to-get-k-consecutive-black-blocks
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是滑动窗口,但是做法可以不像76题那么复杂。题意是让我们把尽可能多的白色涂成黑色,以找到一个连续的,长度为 K 的黑色子串。我直接上代码了,如果看不懂,需要复习之前滑动窗口的题了。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int minimumRecolors(String blocks, int k) {
 3         int count = 0;
 4         for (int i = 0; i < k; i++) {
 5             if (blocks.charAt(i) == 'W') {
 6                 count++;
 7             }
 8         }
 9         
10         int res = count;
11         int n = blocks.length();
12         for (int i = k; i < n; i++) {
13             if (blocks.charAt(i) == 'W') {
14                 count++;
15             }
16             if (blocks.charAt(i - k) == 'W') {
17                 count--;
18             }
19             res = Math.min(res, count);
20         }
21         return res;
22     }
23 }

 

LeetCode 题目总结

posted @ 2023-03-09 01:38  CNoodle  阅读(54)  评论(0编辑  收藏  举报