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