LeetCode 题解工作台
子串能表示从 1 到 N 数字的二进制串
给定一个二进制字符串 s 和一个正整数 n ,如果对于 [1, n] 范围内的每个整数, 其二进制表示都是 s 的 子字符串 ,就返回 true ,否则返回 false 。 子字符串 是字符串中连续的字符序列。 示例 1: 输入: s = "0110", n = 3 输出: true 示例 2: 输…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们注意到,字符串 的长度不超过 ,所以字符串 能表示不超过 个 二进制整数,因此,如果 $n \gt 1000$,那么 肯定不能表示 $[1,.. n]$ 范围内的所有整数的二进制表示。 另外,对于一个整数 ,如果 的二进制表示是 的子串,那么 $\lfloor x / 2 \rfloor$ 的二进制表示也是 的子串。因此,我们只需要判断 $[\lfloor n / 2 \rflo…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给定一个二进制字符串 s 和一个正整数 n,如果对于 [1, n] 范围内的每个整数,其二进制表示都是 s 的 子字符串 ,就返回 true,否则返回 false 。
子字符串 是字符串中连续的字符序列。
示例 1:
输入:s = "0110", n = 3 输出:true
示例 2:
输入:s = "0110", n = 4 输出:false
提示:
1 <= s.length <= 1000s[i]不是'0'就是'1'1 <= n <= 109
解题思路
方法一:脑筋急转弯
我们注意到,字符串 的长度不超过 ,所以字符串 能表示不超过 个 二进制整数,因此,如果 ,那么 肯定不能表示 范围内的所有整数的二进制表示。
另外,对于一个整数 ,如果 的二进制表示是 的子串,那么 的二进制表示也是 的子串。因此,我们只需要判断 范围内的整数的二进制表示是否是 的子串即可。
时间复杂度 ,空间复杂度 ,其中 是字符串 的长度,而 为题目给定的正整数。
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))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?