【LeetCode】393 and 202

393.UTF-8编码验证

在这里插入图片描述
在这里插入图片描述
解法:字符串操作/位操作
该题核心是理解题意规则,可以参考UTF-8 编码验证
题解中的位操作值得学习,通过创建掩码与整数进行与操作,判断整数二进制表示中有多少位1。
python可以用bin和format函数得到整数的二进制表示。

class Solution:
    def validUtf8(self, data):
        """
        :type data: List[int]
        :rtype: bool
        """

        # Number of bytes in the current UTF-8 character
        n_bytes = 0

        # Mask to check if the most significant bit (8th bit from the left) is set or not
        mask1 = 1 << 7

        # Mask to check if the second most significant bit is set or not
        mask2 = 1 << 6
        for num in data:

            # Get the number of set most significant bits in the byte if
            # this is the starting byte of an UTF-8 character.
            mask = 1 << 7
            if n_bytes == 0:
                while mask & num:
                    n_bytes += 1
                    mask = mask >> 1

                # 1 byte characters
                if n_bytes == 0:
                    continue

                # Invalid scenarios according to the rules of the problem.
                if n_bytes == 1 or n_bytes > 4:
                    return False
            else:

                # If this byte is a part of an existing UTF-8 character, then we
                # simply have to look at the two most significant bits and we make
                # use of the masks we defined before.
                if not (num & mask1 and not (num & mask2)):
                    return False
            n_bytes -= 1
        return n_bytes == 0     

202.快乐数

在这里插入图片描述
解法:快慢指针
该题的关键在于能够理解值不会越来越大,最后接近无穷大,即下面第三种情况不存在:
在这里插入图片描述
证明如下:
在这里插入图片描述
因此我们只需对前两种情况进行考虑,其中第二种情况表明在循环过程中会产生一个环。那么该问题就转变为检测链表中是否存在环,即可用快慢指针来解。
在这里插入图片描述
即无论乌龟和兔子在哪,只要兔子比乌龟速度快,那么它们一定会在环内相遇。

class Solution:
    def isHappy(self, n: int) -> bool:
        def getNext(n):
            result = 0
            while n > 0:
                digit = n % 10
                n = n // 10
                result += digit ** 2
            return result
        
        low, fast = n, getNext(n)
        print(low, fast)
        while fast != 1 and low != fast:
            low = getNext(low)
            fast = getNext(getNext(fast))
            # print(low, fast)
        # print(low, fast)
        return fast == 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值