[leetcode]UTF-8 Validation

筅森魡賤 提交于 2020-02-08 13:57:38

位运算

class Solution:
    def validUtf8(self, data: List[int]) -> bool:
        multiByteCount = 0
        for byte in data:
            if multiByteCount > 0: # in multi-byte
                # start with 10
                if byte & 0x80 == 0x80 and byte | 0xbf == 0xbf:
                    multiByteCount -= 1
                else:
                    return False
            elif byte & 0x80 == 0x80: # start with 1, maybe multi-byte
                multiByteCount = 0
                mask = 0x80 >> 1
                while mask > 0 and byte & mask == mask:
                    mask = mask >> 1
                    multiByteCount += 1
                if multiByteCount > 3 or multiByteCount == 0:
                    return False
            else: # start with 0
                continue
        
        if multiByteCount > 0:
            return False
        
        return True

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!