# 30. Substring With Concatenation of All Words 串联所有单词的子串

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).

Difficulty: Hard

### 解法1

``````class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int>res;
if (s.empty()||words.empty()) return res;
int n = (int)words.size(),m=(int)words[0].size();
unordered_map<string,int> m1;
for (auto &a:words) ++m1[a];
for (int i=0;i<=(int)s.size()-n*m;i++)
{
unordered_map<string,int> m2;
int j = 0;
for (j=0;j<n;j++)
{
string t = s.substr(i+j*m,m);
if (m1.find(t)==m1.end()) break;
++m2[t];
if (m2[t]>m1[t]) break;
}
if (j==n) res.push_back(i);
}
return res;
}
};
``````

### 解法2

``````class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int>res;
if (s.empty()||words.empty()) return res;
int n = (int)s.size(),cnt=(int)words.size(),len=(int)words[0].size();
unordered_map<string,int> m1;
for (string s:words) m1[s]++;
for (int i=0;i<len;i++)
{
int left = i,count=0;
unordered_map<string,int> m2;
for (int j=i;j<=n-len;j+=len)
{
string t = s.substr(j,len);
if (m1.count(t))
{
m2[t]++;
if (m2[t]<=m1[t])
count++;
else
{
//从左到右舍弃,直到m2[t]<=m1[t]
while (m2[t]>m1[t])
{
string t1 = s.substr(left,len);
--m2[t1];
if (m2[t1]<m1[t1]) --count;
left += len;
}
}
if (count==cnt)
{
res.push_back(left);
--m2[s.substr(left,len)];
--count;
left += len;
}
}
else //在某次m1[t]不存在,说明此处j与之前的子串不匹配,舍弃,从下个j+len继续
{
m2.clear();
count = 0;
left=j+len;
}
}
}
return res;
}
};
``````