内层循环为子串的长度,以单词的长度为单位增加;若不满足条件立即跳出,满足则继续匹配下一个,至找到整个子串;
外层循环为起点,截止条件为字符串的长度与子串长度的差,以1为单位自加。
用两个哈希表,分别记录输入单词,和每次循环遇到的单词,同时记录单词出现的频率
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
int i=0, n=S.size(), m=L[0].size(), len=m*L.size();
vector<int> res;
unordered_map<string, int> mymap, t;
for (int j=0; j<L.size(); j++) {
mymap[L[j]]++;
}
int start=0;
while (start<=n-len) {
t.clear();
int i=start;
for (; i<start+len; i=i+m) {
string cur=S.substr(i,m);
if (mymap.find(cur)==mymap.end()) {
break;
}else {
t[cur]++;
if (t[cur]>mymap[cur]) {
break;
}
}
}
if (i==start+len) {
res.push_back(start);
}
start++;
}
return res;
}
};
本文介绍了一种用于高效匹配子串的算法,通过内外循环结合哈希表记录单词出现频率,确保在字符串中快速查找指定子串,显著提高了搜索效率。
411

被折叠的 条评论
为什么被折叠?



