Substring with Concatenation of All Words
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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> ans;
if(S.size()==0)return ans;
int m = L.size();
if(m==0)return ans;
int l = L[0].size();
if(l==0)return ans;
if(m*l>S.size())return ans;
map<string,int >mp;
for(int j = 0;j<m;j++)mp[L[j]]++;
for(int i = 0;i<l;i++){
if(i+m*l>S.size())break;
map<string,int> mp1(mp);//记录还有多少个没有匹配到
int count = 0;//记录多少个单词出现重复,相同单词重复次数为1
int c = 0;//记录读入m个单词多少个在List中
for(int k = 0;k<m-1;k++){
string str = S.substr(i+k*l,l);
if(mp1.find(str)!=mp1.end()){
mp1[str]--;
if(mp1[str]==-1)count++;
c++;
}
}
for(int st = i;st+l*m<=S.size();st+=l){
string str = S.substr(st+(m-1)*l,l);
if(mp1.find(str)!=mp1.end()){
mp1[str]--;
if(mp1[str]==-1)count++;
c++;
}
if(c==m && count==0){
ans.push_back(st);
}
str = S.substr(st,l);
if(mp1.find(str)!=mp1.end()){
c--;
mp1[str]++;
if(mp1[str]==0)count--;
}
}
}
return ans;
}
};