一、1784. 检查二进制字符串字段
1.使用0分割。分割出来的结果是含有“1”的串和空串。
class Solution:def checkOnesSegment(self, s: str) -> bool:# 使用0分割return sum(len(c) != 0 for c in s.split("0")) <= 1
2.遍历
class Solution:def checkOnesSegment(self, s: str) -> bool:# 除了前面可以出现0,后面不能出现# 1最后出现的位置必须在0第一次出现位置的前面idx_one = 0idx_zero = 100for i,c in enumerate(s):if c == "0":idx_zero = min(idx_zero,i)else:idx_one = ireturn idx_one < idx_zero
3.寻找“01”串。来自官方题解(. - 力扣(LeetCode))。
class Solution:def checkOnesSegment(self, s: str) -> bool:# 寻找“01”串return "01" not in s
二、2595. 奇偶位数
1.转为字符串
class Solution:def evenOddBit(self, n: int) -> List[int]:# 转为字符串flag = [0]*2 #0位偶1位奇num = str(bin(n)[2:])[::-1]for i,c in enumerate(num):if c == "1":flag[i & 1] += 1return flag
2.位掩码,来自灵神题解(. - 力扣(LeetCode))。
class Solution:def evenOddBit(self, n: int) -> List[int]:# 位掩码MASK = 0x5555 #十六进制的一个5为二进制的0101return [(n & MASK).bit_count(),(n & (MASK >> 1)).bit_count()]
三、2485. 找出中枢整数
1.数学
class Solution:def pivotInteger(self, n: int) -> int:# 数学# x^2 = n*(n+1) // 2m = n*(n+1) // 2return int(m**0.5) if int(m**0.5)*int(m**0.5) == m else -1
另一种写法,来自灵神题解(. - 力扣(LeetCode))。使用isqrt()函数。
class Solution:def pivotInteger(self, n: int) -> int:# 数学2m = n*(n+1) // 2x = isqrt(m)return x if x * x == m else -1
isqrt()函数解释(来自chatgpt):
isqrt()
是求整数平方根(integer square root)的函数,通常用于计算一个整数的平方根并返回最大的整数部分作为结果。在某些编程语言或库中,可能提供了内置的函数来实现这一功能。
整数平方根是指小于或等于给定整数的正整数平方根。例如,对于整数 16,其平方根是 4;对于整数 17,其平方根也是 4,因为整数平方根函数会返回最接近但不超过真实平方根的整数值。
2.打表,方法来自灵神题解。列举出范围内的n->x的字典,再调用。很强,这里就不写代码了。
四、 1704. 判断字符串的两半是否相似
统计
class Solution:def halvesAreAlike(self, s: str) -> bool:# 统计mid = len(s) // 2num = 0for c in s[:mid].lower():if c in 'aeiou':num += 1for c in s[mid:].lower():if c in 'aeiou':num -= 1return num == 0
完
感谢你看到这里!一起加油吧!