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).
1.size()的返回值时unsigned int,计算式会溢出,所以有size的减法一定要转换成int
2.滑动窗口,提升速度
s="abcdaxx" L={"a","b","c","d","e"}
[a]bcdaxx ---> [ab]cdaxx --->[abc]daxx --->[abcd]axx
若a已经出现过切窗口中出现次数==L中的出现次数,则向后滑 a【bcda】xx
若为当前到x的情况,则i+1
class Solution {
public:
map<string, int> count;
map<string, int> use;
map<string, int> index;
vector<int> findSubstring(string S, vector<string> &L)
{
vector<int> rtv;
if(S.size() == 0 || L.size()== 0 || S.size() < L[0].size())return rtv;
int found_count ;
int flag = 0;
int len = L[0].size(),lsize = L.size(),ssize = S.size();
for(int j = 0; j < L.size(); ++j)
count[L[j]]++;
int x = 0;
for(int i = 0; i <= ssize - len * lsize; )
{
x++;
use.clear();
index.clear();
flag = 0;
found_count = 0;
string s = S.substr(i, len);
while(count.find(s) != count.end())
{
use[s]++;
if(use[s] > count[s])break;
if(index.find(s) == index.end())index[s] = i + found_count * len;
++found_count;
if(found_count == lsize)
{
flag = 1;
break;
}
s = S.substr(i + found_count * len, len);
}
if(flag)
{
rtv.push_back(i);
i++;
continue;
}
if(index.find(s) != index.end() && use.find(s) != use.end() && use[s] > count[s])
{
i = index[s] + len;
continue;
}
i++;
}
return rtv;
}
};