[LeetCode] 717. 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.

1比特与2比特字符。

有两种特殊字符:

第一种字符可以用一个比特 0 来表示
第二种字符可以用两个比特(10 或 11)来表示、
给定一个以 0 结尾的二进制数组 bits ,如果最后一个字符必须是一位字符,则返回 true 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1-bit-and-2-bit-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是一道数组的题,我这里给出一个从左往右扫描一遍的解法。题目定义了两种字符,第一种字符可以用一个比特 0 来表示,第二种字符可以用两个比特(10 或 11)来表示。所以当我们从左开始扫描的时候,如果遇到了 1,那么我们遇到的一定是一个2比特字符(10或者11),所以我们遇到1就走两步;如果当前遇到的数字是0,那么就走一步,因为0不能作为一个2比特字符的开头。我们用一个 while 循环来扫描直到跳出循环。如果最后指针在数组最后一个位置停下了则说明最后一位是一个1比特字符。

时间O(n)

空间O(1)

Java实现

复制代码
 1 class Solution {
 2     public boolean isOneBitCharacter(int[] bits) {
 3         int len = bits.length;
 4         int i = 0;
 5         while (i < len - 1) {
 6             if (bits[i] == 1) {
 7                 i += 2;
 8             } else {
 9                 i++;
10             }
11         }
12         return i == len - 1;
13     }
14 }
复制代码

 

LeetCode 题目总结

posted @   CNoodle  阅读(75)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-02-20 [LeetCode] 1245. Tree Diameter
点击右上角即可分享
微信分享提示