原题:
解决方法:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) ins that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
- 首先我们使用一个哈希表来保存字典单词的数量。
- 对每一个字符,用另外一个哈希表来保存找到的单词,如果单词不在字典里面或者单词的数量超过了字典里面的数量,则没有匹配符合要求的起始点。否则如果所有单词全部匹配了,将该起始点加入到返回结果中。
- 我们并不需要搜索原始字符串的每一个字符,对后面长度不符合要求的字符,我们可以直接跳过。
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
int n = s.size(), m = words.size();
if (n < 1 || m < 1 || n < m * words[0].size())
return res;
int len = words[0].size(), totalLen = m * len;
unordered_map<string, int> cnts;
for(auto word: words){
cnts[word]++;
}
for(int i = 0; i < n - (totalLen - 1); i++){
unordered_map<string, int> seen;
int j = 0;
for(;j < m;j++){
string word = s.substr(j*len + i, len);
if (!cnts.count(word))
break;
seen[word]++;
if (seen[word] > cnts[word])
break;
}
if (j == m)
res.push_back(i);
}
return res;
}