717. 1比特与2比特字符

有两种特殊字符。第一种字符可以用一比特0来表示。第二种字符可以用两比特(10 或 11)来表示。

现给一个由若干比特组成的字符串。问最后一个字符是否必定为一个一比特字符。给定的字符串总是由0结束。

示例 1:

输入:
bits = [1, 0, 0]
输出: True
解释:
唯一的编码方式是一个两比特字符和一个一比特字符。所以最后一个字符是一比特字符。
示例 2:

输入:
bits = [1, 1, 1, 0]
输出: False
解释:
唯一的编码方式是两比特字符和两比特字符。所以最后一个字符不是一比特字符。
注意:

1 <= len(bits) <= 1000.
bits[i] 总是0 或 1.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1-bit-and-2-bit-characters

去掉最后的0如果前面的数字都有效就True

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        
        if len(bits)==1:
            return True
        i=0
        while i<len(bits)-1:
            if bits[i]==1:
                i+=1
                if i==len(bits)-1:
                    return False
            i+=1
        return True
        

方法二

class Solution:
    def isOneBitCharacter(self, bits: List[int]) -> bool:
        if len(bits) == 1 or bits[-2] == 0:
            return True
        count = 0
        for i in range(-2, - len(bits) - 1, -1):
            if bits[i] == 1:
                count += 1
            else:
                break
        return bool(1 - count % 2)
原文地址:https://www.cnblogs.com/xxxsans/p/13662970.html