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 wordsexactly 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).
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int n = words.size();
vector<int> res;
if(n<1) return res;
int l = words[0].size();
map<string, int> count1;
int i,j;
for(i = 0; i < n; i++)
++count1[words[i]];
map<string, int> count2;
for(i = 0; i <= (int)s.length()-n*l; i++)
{
count2.clear();
for(j = 0; j < n; j++)
{
string word = s.substr(i+j*l, l);
if(count1.find(word) != count1.end())
{
++count2[word];
if(count2[word]>count1[word])
break;
}
else
break;
}
if(j == n)
res.push_back(i);
}
return res;
}
};