LeetCode 题解工作台
1 比特与 2 比特字符
有两种特殊字符: 第一种字符可以用一比特 0 表示 第二种字符可以用两比特( 10 或 11 )表示 给你一个以 0 结尾的二进制数组 bits ,如果最后一个字符必须是一个一比特字符,则返回 true 。 示例 1: 输入: bits = [1, 0, 0] 输出: true 解释: 唯一的解码方…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们可以直接遍历数组 的前 个元素,每次根据当前元素的值决定跳过多少个元素: - 如果当前元素为 ,则跳过 个元素(表示一个一比特字符);
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
有两种特殊字符:
- 第一种字符可以用一比特
0表示 - 第二种字符可以用两比特(
10或11)表示
给你一个以 0 结尾的二进制数组 bits ,如果最后一个字符必须是一个一比特字符,则返回 true 。
示例 1:
输入: bits = [1, 0, 0] 输出: true 解释: 唯一的解码方式是将其解析为一个两比特字符和一个一比特字符。 所以最后一个字符是一比特字符。
示例 2:
输入:bits = [1,1,1,0] 输出:false 解释:唯一的解码方式是将其解析为两比特字符和两比特字符。 所以最后一个字符不是一比特字符。
提示:
1 <= bits.length <= 1000bits[i]为0或1
解题思路
方法一:直接遍历
我们可以直接遍历数组 的前 个元素,每次根据当前元素的值决定跳过多少个元素:
- 如果当前元素为 ,则跳过 个元素(表示一个一比特字符);
- 如果当前元素为 ,则跳过 个元素(表示一个两比特字符)。
当遍历结束时,如果当前索引等于 ,则说明最后一个字符是一个一比特字符,返回 ;否则,返回 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def isOneBitCharacter(self, bits: List[int]) -> bool:
i, n = 0, len(bits)
while i < n - 1:
i += bits[i] + 1
return i == n - 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Candidates who understand the importance of tracking the next character's position and the array-driven solution approach will likely solve the problem quickly.
- question_mark
Look for candidates who can explain the logic of skipping bits after encountering a 1 and how it ensures correctness.
- question_mark
Candidates who provide a detailed explanation of edge cases, such as handling arrays of length 1 or arrays with consecutive 1's followed by 0, will demonstrate thorough understanding.
常见陷阱
外企场景- error
Candidates may forget to account for the scenario where the array ends with a 0, and incorrectly assume that the last bit is always a one-bit character.
- error
Some candidates might miss the optimization of skipping two bits after a 1, leading to unnecessary iterations.
- error
Candidates may overlook handling edge cases, like the smallest array or cases where there are multiple consecutive 1's followed by 0.
进阶变体
外企场景- arrow_right_alt
What if the array ends with a 1 instead of a 0? How would you handle that case?
- arrow_right_alt
Can this problem be extended to a more general case where bits represent a larger set of characters?
- arrow_right_alt
What if the input array is given in a different encoding format, like a string of 0's and 1's?