【LeetCode】393 and 202

【LeetCode】393 and 202,第1张

【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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5636548.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存