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
or11
).
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 either0
or1
.
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 }