1.字符串的排列
思路:双指针+滑动窗口
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,0length = 0minlen = float('inf')res = ''while right<len(s2):# 向右拓展if s2[right] in dict_:if dict_[s2[right]]>0:#注意要进行判断避免重复字符length+=1dict_[s2[right]]-=1while length==len(s1):#包含了子串啦 这个时候左边要压缩if right-left+1==len(s1):#找最短的return Trueleft+=1if s2[left-1] in dict_:#注意left+1啦 所以要用left-1的字符判断是否出现在dict_中dict_[s2[left - 1]] += 1if dict_[s2[left-1]]>0:#避免重复字符造成的减法length-=1right+=1return 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;}
};