目录
一、题目
给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。
换句话说,第一个字符串的排列之一是第二个字符串的子串。
二、示例
示例1:
输入: s1 = "ab" s2 = "eidbaooo"
输出: True
解释: s2 包含 s1 的排列之一 ("ba").
示例2:
输入: s1= "ab" s2 = "eidboaoo"
输出: False
注意:
- 输入的字符串只包含小写字母
- 两个字符串的长度都在 [1, 10,000] 之间
三、思路
1、暴力法
滑动窗口暴力法,窗口长度为数组 s1 的长度,每次遍历均运用 collections.Counter() 函数计算当前窗口中的字符以及其对应个数,再比较即可。
2、
由于每次都要调用 collections.Counter() 函数,当窗口很长时,时间复杂度很大,因此方法二是对方法一的一种优化。
数组 s1_count 和 数组 window_count 分别记录数组s1 和 当前窗口 window 下的字符及其个数。
遍历时,只需考虑窗口两端的字符即可。再判断 s1_count 和 window_count 是否相等。
四、代码
1、
import collections
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
"""
:param s1: str
:param s2: str
:return: bool
"""
left, right = 0, len(s1)
s1_count = collections.Counter(s1)
for left in range(len(s2) - len(s1) + 1):
# print(s2[left: right])
tmp = collections.Counter(s2[left: right])
if s1_count == tmp:
return True
right += 1
return False
if __name__ == '__main__':
s1 = "ab"
s2 = "eidbaooo"
s = Solution()
ans = s.checkInclusion(s1, s2)
print(ans)
2、
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
# s1,s2长度
n1, n2 = len(s1), len(s2)
# 窗口左右两端下标
left, right = 0, len(s1)
s1_count = [0 for _ in range(26)]
window_count = [0 for i in range(26)]
for char in s1:
s1_count[ord(char) - ord('a')] += 1
for left in range(len(s2) - len(s1) + 1):
window = s2[left: right]
if left == 0:
for char in window:
window_count[ord(char) - ord('a')] += 1
else:
window_count[ord(s2[left - 1]) - ord('a')] -= 1
window_count[ord(s2[right - 1]) - ord('a')] += 1
right += 1
if s1_count == window_count:
return True
return False
if __name__ == '__main__':
s1 = "ab"
s2 = "eidbaooo"
s = Solution()
ans = s.checkInclusion(s1, s2)
print(ans)