[LeetCode Python3] 393. UTF-8 Validation +位处理

该代码实现了一个检查UTF-8编码是否有效的函数。通过位运算判断每个字节是否符合UTF-8编码规范,从单字节到四字节的连续序列进行校验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

393. UTF-8 Validation

symple & 128 == 0 表示symple必为 0xxx xxxx
(symple & 128 == 128) and (symple & 64 == 0) 表示symple必为 10xx xxxx
(symple & 192 == 192) and (symple & 32 == 0) 表示symple必为 110x xxxx
(symple & 224 == 224) and (symple & 16 == 0) 表示symple必为 1110 xxxx
(symple & 240 == 240) and (symple &  8 == 0) 表示symple必为 1111 0xxx

代码:

class Solution:
    def validUtf8(self, data: List[int]) -> bool:
        size = len(data)
        index = 0
        while index < size:
            if data[index] & 128 == 0:
                index += 1
            elif (data[index] & 192 == 192) and (data[index] & 32 == 0):
                index += 1
                if index < size and (data[index] & 128 == 128) and (data[index] & 64 == 0):
                    index += 1
                else:
                    return False
            elif (data[index] & 224 == 224) and (data[index] & 16 == 0):
                index += 1
                for i in range(2):
                    if index < size and (data[index] & 128 == 128) and (data[index] & 64 == 0):
                        index += 1
                    else:
                        return False
            elif (data[index] & 240 == 240) and (data[index] & 8  == 0):
                index += 1
                for i in range(3):
                    if index < size and (data[index] & 128 == 128) and (data[index] & 64 == 0):
                        index += 1
                    else:
                        return False
            else:
                return False
        return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值