目录
串联所有单词的子串
1.题目解析
2.算法思路
3.代码编写
1.题目解析
例:如果 s = "barfoothefoobarman" word = ["foo","bar"]
那么就去s中寻找"foobar"或者"barfoo",返回找到字串的起始位置。
s = "barfoofoobarthefoobarman" word = ["bar","foo","the"]
那么就去s中寻找"barfoothe","barthefoo","foobarthe","foothebar","thef7oobar","thebarfoo".
2.算法思路
哈希表+滑动窗口
哈希表部分
定义hash1存储word中的字符串。
定义两个维护窗口的指针left,right。
定义hash2存储s中的字符串。
滑动窗口部分
进窗口:将长度为word[0].size()的字符存入hash2
判断:看窗口的长度,是否大于寻找字串的长度
出窗口:将长度为word[0].size()的字符从hash2中删除
3.代码编写
class Solution {
public:vector<int> findSubstring(string s, vector<string>& words) {unordered_map<string,int> map1;for(string &str : words){map1[str]++;} vector <int>ans;int len = words[0].size();//单词长度int n = words.size();//if(len > s.size()){return {};}for(int i = 0; i < len; i++){int count = 0;unordered_map<string,int> map2;//存储字符串sfor(int left = i, right = i; right <= s.size()-len; right += len){string in = s.substr(right,len);//进窗口if(++map2[in] <= map1[in])count++;if((right-left+1) > n*len && left < right)//判断1{string out = s.substr(left,len);if(map2[out]-- <= map1[out])//出窗口{count--;}left += len;}if(count == n){ans.push_back(left);}}}return ans;}
};