思路:双指针+滑动窗口
python:
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
dict_={}
for i in s1:
dict_[i] = dict_.get(i,0)+1
# # print('==dict_:',dict_)
left,right =0,0
length = 0
minlen = float('inf')
res = ''
while right<len(s2):# 向右拓展
if s2[right] in dict_:
if dict_[s2[right]]>0:#注意要进行判断避免重复字符
length+=1
dict_[s2[right]]-=1
while length==len(s1):#包含了子串啦 这个时候左边要压缩
if right-left+1==len(s1):#找最短的
return True
left+=1
if s2[left-1] in dict_:#注意left+1啦 所以要用left-1的字符判断是否出现在dict_中
dict_[s2[left - 1]] += 1
if dict_[s2[left-1]]>0:#避免重复字符造成的减法
length-=1
right+=1
return False
c++:
class Solution {
public:
bool checkInclusion(string s1, string s2) {
map<char,int> dict_;
for (int k=0;k<s1.size();k++)
{
dict_[s1[k]]++;
}
// map <char,int>::iterator itor = dict_.begin();
// //debug
// for(;itor!=dict_.end();itor++)
// {
// cout<<itor->first<<" "<<itor->second<<endl;
// }
int right=0;
int left=0;
int remain_legth =0;
while (right<s2.size())
{
// cout<<"=dict_[s2[right]:"<<dict_[s2[right]]<<endl;
if(dict_[s2[right]]>0)
{
remain_legth+=1;
}
dict_[s2[right]]-=1;
while(remain_legth==s1.size())
{
if(right-left+1==s1.size())
{
return true;
}
left+=1;
dict_[s2[left-1]]+=1;
if (dict_[s2[left-1]]>0)
{
remain_legth-=1;
}
}
right+=1;
}
return false;
}
};