You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9]
.
(order does not matter).
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
unordered_map<string,int> pattern,ref;
vector<int> res;
for (int i=0; i<L.size(); i++)
++pattern[L[i]];
int N=L[0].size();
int M=L.size();
for (int i=0; i<=(int)S.size()-N*M;i++){
ref.clear();
int j=0;
for (;j<M;j++){
string tmp=S.substr(i+j*N,N);
if (pattern[tmp]==0)
break;
if (++ref[tmp]>pattern[tmp])
break;
}
if (j==M)
res.push_back(i);
}
return res;
}
};
code比较简单,网上有用sliding window的线性解,以后再看。。注意size这个地方要加(int), 否则返回unsigned int 会死循环