[leetcode] 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).

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 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.

分析:题目比较有意思,给两个特殊的字符,一个用0表示,另一个使用10、11表示。然后给你一个数组,要求判断这个数组最后一个字符是不是1bit。用递归法来做非常方便。

 1 class Solution {
 2     public boolean isOneBitCharacter(int[] bits) {
 3         int cur=0;
 4         return helper(bits,cur);
 5     }
 6     private boolean helper(int[] bits, int cur) {
 7         if ( cur == bits.length-2 && bits[cur] == 1 ) return false;
 8         if ( cur == bits.length - 1 ) return true;
 9         return bits[cur]==0?helper(bits,cur+1):helper(bits, cur+2);
10     }
11 }

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9270381.html