LeetCode 题解工作台

1 比特与 2 比特字符

有两种特殊字符: 第一种字符可以用一比特 0 表示 第二种字符可以用两比特( 10 或 11 )表示 给你一个以 0 结尾的二进制数组 bits ,如果最后一个字符必须是一个一比特字符,则返回 true 。 示例 1: 输入: bits = [1, 0, 0] 输出: true 解释: 唯一的解码方…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们可以直接遍历数组 的前 个元素,每次根据当前元素的值决定跳过多少个元素: - 如果当前元素为 ,则跳过 个元素(表示一个一比特字符);

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有两种特殊字符:

  • 第一种字符可以用一比特 0 表示
  • 第二种字符可以用两比特(10 或 11)表示

给你一个以 0 结尾的二进制数组 bits ,如果最后一个字符必须是一个一比特字符,则返回 true

 

示例 1:

输入: bits = [1, 0, 0]
输出: true
解释: 唯一的解码方式是将其解析为一个两比特字符和一个一比特字符。
所以最后一个字符是一比特字符。

示例 2:

输入:bits = [1,1,1,0]
输出:false
解释:唯一的解码方式是将其解析为两比特字符和两比特字符。
所以最后一个字符不是一比特字符。

 

提示:

  • 1 <= bits.length <= 1000
  • bits[i]01
lightbulb

解题思路

方法一:直接遍历

我们可以直接遍历数组 bits\textit{bits} 的前 n1n-1 个元素,每次根据当前元素的值决定跳过多少个元素:

  • 如果当前元素为 00,则跳过 11 个元素(表示一个一比特字符);
  • 如果当前元素为 11,则跳过 22 个元素(表示一个两比特字符)。

当遍历结束时,如果当前索引等于 n1n-1,则说明最后一个字符是一个一比特字符,返回 true\text{true};否则,返回 false\text{false}

时间复杂度 O(n)O(n),其中 nn 是数组 bits\textit{bits} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
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
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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?

help

常见问题

外企场景

1 比特与 2 比特字符题解:数组·driven | LeetCode #717 简单