**题目:Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string’s permutations is the substring of the second string.
Example 1:
Input: s1 = “ab” s2 = “eidbaooo”
Output: True
Explanation: s2 contains one permutation of s1 (“ba”).
Example 2:
Input:s1= “ab” s2 = “eidboaoo”
Output: False
Constraints:
The input strings only contain lower case letters.
The length of both given strings is in range [1, 10,000].**
首先来分析一下这道题目,本题要求s1的全排列是否在s2当中出现过,这里的全排列需要特别注意,如果你真的将s1的全排列求出,然后再去s2中进行检验那就费了太多力气。实际上要检验s1的全排列,只需要统计s1当中每个字母的出现次数,如果s2中有一段等长字符的每个字母出现次数的统计与s1相同,那就证明s2当中存在s1的全排列。
从这个点出发,然后借助双指针便可以大大提高算法的效率。left、right为双指针,hash_map记录s1中各个字母的出现次数。如果right位置处的字母在s1中出现且统计值大于0,那就将hash_map中该字母的出现次数减1,right右移。如果没有出现,那就将right右移,同时left移动到right位置。如果出现但是在hash_map当中统计值为0,则将left右移直到遇到和此时right处字母相同为止。
以下为具体代码实现:
def checkInclusion(s1,s2):
if len(s1)>len(s2):
return False
hash_={}
for s in s1:
if s in hash_:
hash_[s]+=1
else:
hash_[s]=1
l=len(s1)
left=0
right=0
l_temp=l
hash_map=hash_.copy()
while left<len(s2)-l+1:
if l_temp==0:
return True
if s2[right] in hash_:
if hash_[s2[right]]>0:
hash_[s2[right]]-=1
right+=1
l_temp-=1
else:
while s2[left]!=s2[right]:
hash_[s2[left]]+=1
left+=1
l_temp+=1
left+=1
right+=1
else:
right+=1
left=right
l_temp=l
hash_=hash_map.copy()
return False