题目链接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/
题意:
给定一个字符串 s 和一些 长度相同 的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符 ,但不需要考虑 words 中单词串联的顺序。
方法:两张哈希表,一张存储word的映射关系,一张存储当前遍历字符串的映射关系,运用到了滑动窗口,字符串的切割
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ret;
int left,right,cnt;//滑动窗口左侧坐标,滑动窗口右侧坐标,统计到目前总共几个词
int len=words.size(),step=words[0].size();//记录words里总共几个词,滑动步长
int s_size = s.size();//统计字符串里有多少个字符
unordered_map<string,int> mp1;//哈希表1存储words的相应映射关系<字符串,出现次数>
for(auto& word:words)//更新哈希表1
{
mp1[word]++;
}
unordered_map<string,int> mp2;//哈希表2存储当前字符串的映射关系<字符串,出现次数>
for(int i=0;i<step;i++)//解决不是从0开始从而造成的偏移
{
left=i,right=i;//嵌套循环只会影响滑动窗口左侧坐标和右侧坐标
cnt = 0;
mp2.clear();
while(right<s_size)
{
string tmp = s.substr(right,step);//截取字符串
if(mp1.find(tmp)==mp1.end())//如果当前字符串不在哈希表1中,放弃前面的那一段,并且进行重置哈希表2和计数器
{
left = right+step;
cnt = 0;
mp2.clear();
}
else
{
mp2[tmp]++;//更新哈希表2
while(mp2[tmp]>mp1[tmp])//有个别词汇超过了要求的次数,滑动窗口左侧坐标右移
{
string tmp1 = s.substr(left,step);//截取对应的字符串
mp2[tmp1]--;//哈希表2更新
cnt--;//计数器自减
left+=step;//滑动窗口左侧坐标右移
}
if(mp2[tmp]<=mp1[tmp])//没超过去就统计次数
{
cnt++;//统计次数
if(cnt==len) ret.emplace_back(left);//如果刚好满len次,就把left的坐标放入ret中
}
}
right+=step;//滑动窗口右侧坐标右移
}
}
return ret;
}
};