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, 0, 0] => True
[1, 0, 1, 0] => False
Note:
1 <= len(bits) <= 1000.
bits[i] is always 0 or 1.
Python:
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
return True if len(bits) == 1 else False if len(bits) == 0 else self.isOneBitCharacter(bits[ 1 if bits[0] == 0 else 2 :])
Java:
class Solution {
public boolean isOneBitCharacter(int[] bits) {
boolean isOne = false;
for(int i = 0; i < bits.length; i++) {
if(bits[i] == 1) {
isOne = false;
i++;
} else {
isOne = true;
}
}
return isOne;
}
}
Go:
func isOneBitCharacter(bits []int) bool {
if len(bits) == 0 {
return false
} else if len(bits) == 1 {
return true
} else if bits[0] == 1{
return isOneBitCharacter(bits[2:])
} else {
return isOneBitCharacter(bits[1:])
}
}
网友评论