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 @ 2022-11-03 18:33  iyiluo  阅读(34)  评论(0)    收藏  举报