LeetCode 题解工作台

检查一个字符串是否包含所有长度为 K 的二进制子串

给你一个二进制字符串 s 和一个整数 k 。如果所有长度为 k 的二进制字符串都是 s 的子串,请返回 true ,否则请返回 false 。 示例 1: 输入: s = "00110110", k = 2 输出: true 解释: 长度为 2 的二进制串包括 "00","01","10" 和 "1…

category

5

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 哈希·表·结合·string

bolt

答案摘要

首先,对于一个长度为 的字符串 ,长度为 的子串的个数为 $n - k + 1$,如果 $n - k + 1 < 2^k$,则一定存在长度为 的二进制串不是 的子串,返回 `false`。 接下来,我们遍历字符串 ,将所有长度为 的子串存入集合 ,最后判断集合 的大小是否等于 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二进制字符串 s 和一个整数 k 。如果所有长度为 k 的二进制字符串都是 s 的子串,请返回 true ,否则请返回 false

 

示例 1:

输入:s = "00110110", k = 2
输出:true
解释:长度为 2 的二进制串包括 "00","01","10" 和 "11"。它们分别是 s 中下标为 0,1,3,2 开始的长度为 2 的子串。

示例 2:

输入:s = "0110", k = 1
输出:true
解释:长度为 1 的二进制串包括 "0" 和 "1",显然它们都是 s 的子串。

示例 3:

输入:s = "0110", k = 2
输出:false
解释:长度为 2 的二进制串 "00" 没有出现在 s 中。

 

提示:

  • 1 <= s.length <= 5 * 105
  • s[i] 不是'0' 就是 '1'
  • 1 <= k <= 20
lightbulb

解题思路

方法一:哈希表

首先,对于一个长度为 nn 的字符串 ss,长度为 kk 的子串的个数为 nk+1n - k + 1,如果 nk+1<2kn - k + 1 < 2^k,则一定存在长度为 kk 的二进制串不是 ss 的子串,返回 false

接下来,我们遍历字符串 ss,将所有长度为 kk 的子串存入集合 ssss,最后判断集合 ssss 的大小是否等于 2k2^k

时间复杂度 O(n×k)O(n \times k),空间复杂度 O(n)O(n)。其中 nn 是字符串 ss 的长度。

1
2
3
4
5
6
7
8
9
class Solution:
    def hasAllCodes(self, s: str, k: int) -> bool:
        n = len(s)
        m = 1 << k
        if n - k + 1 < m:
            return False
        ss = {s[i : i + k] for i in range(n - k + 1)}
        return len(ss) == m
speed

复杂度分析

指标
时间complexity is O(n) because each character is processed once in the sliding window. Space complexity is O(2^k) for storing unique binary codes, which is efficient for k <= 20. Rolling hash reduces overhead compared to storing substrings directly.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Consider using a hash set instead of nested loops for substring existence checks.

  • question_mark

    Notice that only substrings of length k matter; extra characters outside windows are irrelevant.

  • question_mark

    Think about how bit manipulation can represent substrings compactly.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle k > length of s, which should immediately return false.

  • error

    Recomputing substrings instead of using a rolling window, causing TLE on large strings.

  • error

    Incorrectly counting duplicates instead of unique substrings when verifying all codes.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check if a string contains all ternary codes of size k with characters '0', '1', '2'.

  • arrow_right_alt

    Return the first missing binary code of length k if not all exist in s.

  • arrow_right_alt

    Count how many binary codes of size k are present in s instead of a boolean check.

help

常见问题

外企场景

检查一个字符串是否包含所有长度为 K 的二进制子串题解:哈希·表·结合·string | LeetCode #1461 中等