717. 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. Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1.
思路:
这道题挺简单的,主要是需要理解题目,用一个while循环,遇见1就把索引加2,否则加1,如果在循环中碰见索引等于长度-1,那么就返回True,否则循环结束就返回False
代码:
class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ a = len(bits) i = 0 while i < a: if i == a - 1: return True if bits[i] == 1: i += 2 else: i += 1 return False