【优选算法】滑动窗口 串联所有单词的⼦串
算法思路:
如果我们把每⼀个单词看成⼀个⼀个字⺟,问题就变成了找到「字符串中所有的字⺟异位词」。⽆⾮就是之前处理的对象是⼀个⼀个的字符,我们这⾥处理的对象是⼀个⼀个的单词。
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ret;
unordered_map<string,int> hash1;
for(auto& s:words) hash1[s]++;
int len=words[0].size(),m=words.size();
for(int i=0;i<len;i++)
{
unordered_map<string,int> hash2;
for(int left=i,right=i,count=0;right+len<=s.size();right+=len)
{
string in=s.substr(right,len);
hash2[in]++;
if(hash2[in]<=hash1[in]) count++;
if(right-left+1>len*m)
{
string out=s.substr(left,len);
if(hash2[out]<=hash1[out]) count--;
hash2[out]--;
left+=len;
}
if(count==m) ret.push_back(left);
}
}
return ret;
}
};