LeetCode 题解工作台
找出第 N 个二进制字符串中的第 K 位
给你两个正整数 n 和 k ,二进制字符串 S n 的形成规则如下: S 1 = "0" 当 i > 1 时, S i = S i-1 + "1" + reverse(invert(S i-1 )) 其中 + 表示串联操作, reverse(x) 返回反转 x 后得到的字符串,而 invert(x)…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · string·结合·递归
答案摘要
我们可以发现,对于 ,其前半部分和 是一样的,而后半部分是 的反转取反。因此我们可以设计一个函数 $dfs(n, k)$,表示第 个字符串的第 位字符。答案即为 $dfs(n, k)$。 函数 $dfs(n, k)$ 的计算过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·递归 题型思路
题目描述
给你两个正整数 n 和 k,二进制字符串 Sn 的形成规则如下:
S1 = "0"- 当
i > 1时,Si = Si-1 + "1" + reverse(invert(Si-1))
其中 + 表示串联操作,reverse(x) 返回反转 x 后得到的字符串,而 invert(x) 则会翻转 x 中的每一位(0 变为 1,而 1 变为 0)。
例如,符合上述描述的序列的前 4 个字符串依次是:
S1 = "0"S2 = "011"S3 = "0111001"S4 = "011100110110001"
请你返回 Sn 的 第 k 位字符 ,题目数据保证 k 一定在 Sn 长度范围以内。
示例 1:
输入:n = 3, k = 1 输出:"0" 解释:S3 为 "0111001",其第 1 位为 "0" 。
示例 2:
输入:n = 4, k = 11 输出:"1" 解释:S4 为 "011100110110001",其第 11 位为 "1" 。
示例 3:
输入:n = 1, k = 1 输出:"0"
示例 4:
输入:n = 2, k = 3 输出:"1"
提示:
1 <= n <= 201 <= k <= 2n - 1
解题思路
方法一:分类讨论 + 递归
我们可以发现,对于 ,其前半部分和 是一样的,而后半部分是 的反转取反。因此我们可以设计一个函数 ,表示第 个字符串的第 位字符。答案即为 。
函数 的计算过程如下:
- 如果 ,那么答案为 ;
- 如果 是 的幂次方,那么答案为 ;
- 如果 ,说明 在前半部分,答案为 ;
- 否则,答案为 ,其中 表示异或运算。
时间复杂度 ,空间复杂度 。其中 为题目给定的 。
class Solution:
def findKthBit(self, n: int, k: int) -> str:
def dfs(n: int, k: int) -> int:
if k == 1:
return 0
if (k & (k - 1)) == 0:
return 1
m = 1 << n
if k * 2 < m - 1:
return dfs(n - 1, k)
return dfs(n - 1, m - k) ^ 1
return str(dfs(n, k))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each recursive call reduces n by 1. Space complexity is O(n) due to the recursion stack. No full string is constructed, preventing exponential growth. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Notice how recursion mirrors both reversing and inverting previous strings.
- question_mark
Check if candidates attempt full string construction versus index mapping.
- question_mark
Ask why the middle index is special and how it simplifies recursion.
常见陷阱
外企场景- error
Attempting to construct the entire S_n, leading to exponential memory use.
- error
Miscomputing the mirrored index for k > middle, causing wrong bit retrieval.
- error
Forgetting to invert the bit after mapping k to the mirrored position.
进阶变体
外企场景- arrow_right_alt
Return a substring from position l to r in S_n using the same recursive mapping.
- arrow_right_alt
Count the number of '1's in S_n up to position k without full construction.
- arrow_right_alt
Modify the middle bit from '1' to '0' and analyze the new recursive pattern.