LeetCode 题解工作台

子串能表示从 1 到 N 数字的二进制串

给定一个二进制字符串 s 和一个正整数 n ,如果对于 [1, n] 范围内的每个整数, 其二进制表示都是 s 的 子字符串 ,就返回 true ,否则返回 false 。 子字符串 是字符串中连续的字符序列。 示例 1: 输入: s = "0110", n = 3 输出: true 示例 2: 输…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 滑动窗口(状态滚动更新)

bolt

答案摘要

我们注意到,字符串 的长度不超过 ,所以字符串 能表示不超过 个 二进制整数,因此,如果 $n \gt 1000$,那么 肯定不能表示 $[1,.. n]$ 范围内的所有整数的二进制表示。 另外,对于一个整数 ,如果 的二进制表示是 的子串,那么 $\lfloor x / 2 \rfloor$ 的二进制表示也是 的子串。因此,我们只需要判断 $[\lfloor n / 2 \rflo…

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个二进制字符串 s 和一个正整数 n,如果对于 [1, n] 范围内的每个整数,其二进制表示都是 s子字符串 ,就返回 true,否则返回 false 

子字符串 是字符串中连续的字符序列。

 

示例 1:

输入:s = "0110", n = 3
输出:true

示例 2:

输入:s = "0110", n = 4
输出:false

 

提示:

  • 1 <= s.length <= 1000
  • s[i] 不是 '0' 就是 '1'
  • 1 <= n <= 109
lightbulb

解题思路

方法一:脑筋急转弯

我们注意到,字符串 ss 的长度不超过 10001000,所以字符串 ss 能表示不超过 10001000 个 二进制整数,因此,如果 n>1000n \gt 1000,那么 ss 肯定不能表示 [1,..n][1,.. n] 范围内的所有整数的二进制表示。

另外,对于一个整数 xx,如果 xx 的二进制表示是 ss 的子串,那么 x/2\lfloor x / 2 \rfloor 的二进制表示也是 ss 的子串。因此,我们只需要判断 [n/2+1,..n][\lfloor n / 2 \rfloor + 1,.. n] 范围内的整数的二进制表示是否是 ss 的子串即可。

时间复杂度 O(m2×logm)O(m^2 \times \log m),空间复杂度 O(logn)O(\log n),其中 mm 是字符串 ss 的长度,而 nn 为题目给定的正整数。

1
2
3
4
5
6
class Solution:
    def queryString(self, s: str, n: int) -> bool:
        if n > 1000:
            return False
        return all(bin(i)[2:] in s for i in range(n, n // 2, -1))
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates an understanding of sliding window techniques.

  • question_mark

    Candidate leverages bit manipulation for optimizing binary substring checks.

  • question_mark

    Candidate uses a hash table effectively for substring tracking and lookups.

warning

常见陷阱

外企场景
  • error

    Failing to recognize that only substrings of length at most 30 are needed due to binary number size constraints.

  • error

    Not efficiently checking for the presence of all required substrings by brute force.

  • error

    Overcomplicating the problem by trying to check all possible substrings without using efficient data structures like hash tables.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the range of numbers is extremely large? Can the approach be adapted for larger ranges efficiently?

  • arrow_right_alt

    Can this approach work if the binary string is not guaranteed to be contiguous or has interruptions?

  • arrow_right_alt

    What happens if we need to handle non-binary strings or strings with different character sets?

help

常见问题

外企场景

子串能表示从 1 到 N 数字的二进制串题解:滑动窗口(状态滚动更新) | LeetCode #1016 中等