串联所有单词的字串 --- 滑动窗口
目录
一:题目
二:算法原理分析
三:代码实现
一:题目
题目链接:30. 串联所有单词的子串 - 力扣(LeetCode)
同类型基础题链接:438. 找到字符串中所有字母异位词 - 力扣(LeetCode)
二:算法原理分析
三:代码实现
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words)
{
int len = words[0].size(), m = words.size();
vector<int> ret;
unordered_map<string, int> hash1;//words中各个字符串出现的次数
for (auto& e : words)
{
hash1[e]++;
}
//滑动窗口执行len次
for (int i = 0; i < len; i++)
{
unordered_map<string, int> hash2;
for (int left = i, right = i, cont = 0; right < s.size(); right += len)
{
//进窗口+维护cont
string in = s.substr(right, len);//取字串
hash2[in]++;
if (hash1.count(in) && hash2[in] <= hash1[in])
cont++;
//判断
if (right - left + 1 > len * m)
{
//出窗口 +维护cont
string out = s.substr(left, len);
if (hash1.count(out) && hash2[out] <= hash1[out])
cont--;
hash2[out]--;
left += len;
}
if (cont == m)
{
ret.push_back(left);
}
}
}
return ret;
}
};