小黑代码
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
# 字符串长度
n_s1 = len(s1)
n_s2 = len(s2)
if n_s1 > n_s2:
return False
# s1的字符计数字典
count_s1 = [0] * 26
# 窗口计数字典
count_window = [0] * 26
# 寻找初始窗口
for i in range(n_s1):
count_s1[ord(s1[i])-97] += 1
count_window[ord(s2[i])-97] += 1
# 初始条件是否符合
if count_s1 == count_window:
return True
for i in range(n_s1, n_s2):
count_window[ord(s2[i])-97] += 1
count_window[ord(s2[i-n_s1])-97] -= 1
if count_s1 == count_window:
return True
return False
滑动窗口法
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
# 字符串长度
n_s1 = len(s1)
n_s2 = len(s2)
if n_s1 > n_s2:
return False
# 差值字典
diff_map = [0] * 26
# 计算初始窗口差值
for i in range(n_s1):
diff_map[ord(s1[i])-97] += 1
diff_map[ord(s2[i])-97] -= 1
# 计算差值
diff = sum([abs(i) for i in diff_map])
if not diff:
return True
# 开始滑动窗口
for i in range(n_s1, n_s2):
# 窗口头部字符在差值大于0
if diff_map[ord(s2[i-n_s1])-97] >= 0:
diff += 1
else:
diff -= 1
diff_map[ord(s2[i-n_s1])-97] += 1
# 窗口尾部字符在差值大于0
if diff_map[ord(s2[i])-97] > 0:
diff -= 1
else:
diff += 1
diff_map[ord(s2[i])-97] -= 1
if not diff:
return True
return False
双指针
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
# 字符串长度
n_s1 = len(s1)
n_s2 = len(s2)
if n_s1 > n_s2:
return False
# 差值数组
diff_map = [0] * 26
for i in range(n_s1):
diff_map[ord(s1[i])-97] -= 1
# 开始进行双指针操作
left = 0
right = 0
while right < n_s2:
# left右移动
while diff_map[ord(s2[right])-97] >= 0:
diff_map[ord(s2[left])-97] -= 1
left += 1
diff_map[ord(s2[right])-97] += 1
right += 1
if right - left == n_s1:
return True
return False
小黑生活
到达重庆江北机场
购买长江索道门票
前往解放碑吃火锅
前往长江索道,一路遛弯看夜景
到了发现洪崖洞和朝天门刚好关灯了
睡了一宿
早上出发喝喜茶吃李板凳小面
沿着江边逛逛
洪崖洞里灌一逛
前往白象居