leetcode-717-easy

1-bit and 2-bit Characters

We have two special characters:

The first character can be represented by one bit 0.
The second character can be represented by two bits (10 or 11).
Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.

Example 1:

Input: bits = [1,0,0]
Output: true
Explanation: The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
Example 2:

Input: bits = [1,1,1,0]
Output: false
Explanation: The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
Constraints:

1 <= bits.length <= 1000
bits[i] is either 0 or 1.

思路一:递归,递归终止条件完全分类,共计三种情况

  • 剩余 0 bit -> false
  • 剩余 1 bit -> 0 or 1
  • 剩余大于 1 bit -> 继续判断

对着三种情况进行判断即可

public boolean isOneBitCharacter(int[] bits) {
    return isOneBitCharacter(bits, 0);
}

public boolean isOneBitCharacter(int[] bits, int begin) {
    if (begin == bits.length - 1) {
        return bits[begin] == 0;
    } else if (begin < bits.length - 1) {
        if (bits[begin] == 0) {
            return isOneBitCharacter(bits, begin + 1);
        } else {
            return isOneBitCharacter(bits, begin + 2);
        }
    } else {
        return false;
    }
}
posted @   iyiluo  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示