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) in s 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).
思路: 利用hash表匹配
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
if (s.empty() || words.empty()) return res;
int n=words[0].size();
int m = words.size();
unordered_map<string, int> record; //定位words中每个单词出现的次数
for (int i = 0; i < m; i++)
record[words[i]]++;
unordered_map<string, int> cur; //匹配record
cout << s.length() << ' ' << s.size() << endl;
int lim = s.length() - n*m;
for (int i = 0; i <= lim; i++){
cur.clear();
int j;
for (j = i; j < i + m*n; j = j + n){
if (find(words.begin(), words.end(), s.substr(j, n)) != words.end()){
cur[s.substr(j, n)]++;
if (cur[s.substr(j, n)]>record[s.substr(j, n)])
break;
}
else
break;
}
if (j == i + m*n)
res.push_back(i);
}
return res;
}
};