版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/83051007
Description
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).
Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
Example
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.
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.
Note
- 1 <= len(bits) <= 1000.
- bits[i] is always 0 or 1.
Solution
当前数字如果是1的话,则下一个数字可以为0或者1,将下标往后移两位;如果当前数字是0的话,则判断当前位置是不是最后一位,如果是,则答案题目要求,返回true,如果不是,则继续将位置向后移动一位。
class Solution {
public boolean isOneBitCharacter(int[] bits) {
int i = 0;
while(i < bits.length) {
if(bits[i] == 1) {
i+=2;
} else {
if(i == bits.length - 1)
return true;
i++;
}
}
return false;
}
}