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> res;
vector<int> findSubstring(string s, vector<string>& words) {
int n=words.size();
if(n==0) return res;
int m=words[0].size();
map<string,int> dic,found;
for(int i=0;i<n;++i)
{
if(dic.find(words[i])==dic.end())
dic[words[i]]=1;
else dic[words[i]]++;
}
int start=0,cur,real;
while(s.size()-start>=n*m)
{
cur=start;
found.clear();
real=0;
while(cur<start+n*m)
{
string tmp = s.substr(cur,m);
if(dic.find(tmp)!=dic.end())
{
if(found.find(tmp)==found.end()) found[tmp]=1;
else found[tmp]++;
if(found[tmp]<=dic[tmp]) real++;
cur+=m;
}
else
break;
}
if(real==n) res.push_back(start);
start++;
}
return res;
}
};