Given two strings s1 and s2, write a function to determine whether s2 contains the permutation of s1. In other words, one of the permutations of the first string is a substring of the second string.
Example 1: Input: s1 = "ab" s2 = "eidbaooo" Output: True
Explanation: s2 contains one of the permutations of s1 ("ba").
Example 2: Input: s1= "ab" s2 = "eidboaoo" Output: FalseSource: LeetCode
Link: https://leetcode-cn.com/problems/permutation-in-string
This question is very similar to the solution of " 438. Find all letter dyslexia in a string "
Method 1: Use the sliding window to compare the characters in the sliding window with the string in s1, if they are the same, it is considered
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1)>len(s2): return False
record=Counter(s1)
length=len(s1)
win={}
l=0
rst=False # 不同处
for r,c in enumerate(s2):
if c not in record.keys():
win.clear()
l=r+1
else:
win[c]=win.get(c,0)+1
if r-l+1==length:
if win==record:
rst=True # 不同处
win[s2[l]]-=1
l+=1
return rst
Method 2: A variant of method 1
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
need = {}
window = {}
for i in s1:
if i in need:
need[i] += 1
else:
need[i] = 1
print(need,len(need))
left = 0
right = 0
valid = 0
while right < len(s2):
c = s2[right]
right += 1
if c in need:
# 窗口开始,在不在need和window中
if c in window:
window[c] += 1
else:
window[c] = 1
# 判断窗口函数值是否相同,相同则标记加1
if window[c] == need[c]:
valid += 1
if right - left >= len(s1):
# 当窗口长度大于目标字符串长度时
# 若valid等于字典need的长度时,即所有字符都比对完成时,还回 true
if valid == len(need):
return True
# 移动左边界,把最左边的字符清除出window
d = s2[left]
left += 1
if d in need:
# 如果这时需要清除的字符d在字典need中,则需要处理标记值valid和窗口值
if window[d] == need[d]:
valid -= 1
window[d] -= 1
return False