题目
输入: s1 = “ab” s2 = “eidbaooo”
输出: True
解释: s2 包含 s1 的排列之一 (“ba”).
题解
1 sort字符串对比
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
# 窗口为len(s1),然后对窗口内的以及s1都sort后对比
len1 = len(s1)
pattern = "".join(sorted(s1))
for i in range(len(s2)):
tmp = s2[i:len1+i]
if "".join(sorted(tmp)) == pattern:
return True
return False
2 字典统计窗口字母 key = 字母,value = 出现次数
- 因为是小写字母,所以可以映射到0-25
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s2) < len(s1):
return False
# ord('a') = 97
# 计算s1的字符状态
stat1 = [0] * 26
for ch in s1:
stat1[ord(ch) - 97] += 1
# 初始化滑动窗口
stat2 = [0] * 26
for i in range(len(s1)):
stat2[ord(s2[i]) - 97] += 1
if stat1 == stat2:
return True
# 移动滑动窗口
for i in range(len(s1), len(s2)):
stat2[ord(s2[i]) - 97] += 1
stat2[ord(s2[i - len(s1)]) - 97] -= 1
if stat1 == stat2:
return True
return False