小黑代码1:滑动窗口
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# 字符串长度
n_s = len(s)
n_p = len(p)
if n_s < n_p:
return []
# 差值数组
arr = [0] * 26
# 初始窗口
for i in range(n_p):
arr[ord(p[i])-97] -= 1
arr[ord(s[i])-97] += 1
# 计算初始窗口差值
diff = sum([abs(t) for t in arr])
# 结果数组
results = []
if not diff:
results.append(0)
# 滑动窗口操作
for i in range(n_s-n_p):
if arr[ord(s[i])-97] <= 0:
diff += 1
else:
diff -= 1
arr[ord(s[i])-97] -= 1
if arr[ord(s[i+n_p])-97] < 0:
diff -= 1
else:
diff += 1
arr[ord(s[i+n_p])-97] += 1
if not diff:
results.append(i+1)
return results`class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# 字符串长度
n_s = len(s)
n_p = len(p)
if n_s < n_p:
return []
# 差值数组
arr = [0] * 26
for i in range(n_p):
arr[ord(p[i])-97] -= 1
# 定义双指针
head = 0
tail = 0
# 结果数组
results = []
# 进行双指针操作
while tail < n_s:
# 头指针右移动
while arr[ord(s[tail])-97] >= 0:
arr[ord(s[head])-97] -= 1
head += 1
arr[ord(s[tail])-97] += 1
tail += 1
if tail - head == n_p:
results.append(head)
return results`
小黑代码2:双指针法
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# 字符串长度
n_s = len(s)
n_p = len(p)
if n_s < n_p:
return []
# 差值数组
arr = [0] * 26
for i in range(n_p):
arr[ord(p[i])-97] -= 1
# 定义双指针
head = 0
tail = 0
# 结果数组
results = []
# 进行双指针操作
while tail < n_s:
# 头指针右移动
while arr[ord(s[tail])-97] >= 0:
arr[ord(s[head])-97] -= 1
head += 1
arr[ord(s[tail])-97] += 1
tail += 1
if tail - head == n_p:
results.append(head)
return results
小黑生活
吃黄姐火锅
重庆小巷子里闲逛,前往中山四路
到达中山四路
坐轻轨去李子坝,吃苕皮,看穿楼轻轨
前往重庆江北机场
发现海底捞学生优惠用不了了
复查眼睛,喝喜茶
来一碗门框卤煮
抢去西藏的票
搓澡汗蒸,身上全是泥
疯狂星期四,见三年的研究生线上同门,一起喝了北冰洋,好久不摸零钱了