您的位置:首页 > 其它

【ATT】Substring with Concatenation of All Words

2013-10-26 16:24 344 查看
和minimum window string的原理一样。维护一个window

vector<int> findSubstring(string S, vector<string> &L) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> res;
if(S.empty()||L.empty())
return res;
unordered_map<string,int> dict;
vector<int> needed(L.size(),0);
int i,j;
//precess
for(i=0;i<L.size();i++)
{
if(dict.find(L[i])==dict.end())
{
dict[L[i]] = i;   //先对L中每个字符串编号。
needed[i] = 1;    //统计每个字符串出现的次数。
}else
needed[dict[L[i]]]++;
}

int sLen = S.size();
int LLen = L.size();
int len = L[0].size();

vector<int> pos(sLen,-1);  //pos[i]==-1,表示[i,i+len-1]组成的字符串不在L中,否则,存储其编号

for(i=0;i<=sLen-len;i++)
{
string str = S.substr(i,len);
if(dict.find(str)!=dict.end())
pos[i] = dict[str];
}

for(int offset = 0;offset<len;offset++)
{
int count = 0;
vector<int> found(LLen,0);  //统计当前window发现的L中每个字符串个数
int begin = offset,end = offset;
while(end<=sLen-len)
{
if(pos[end]==-1)  //cur str not in L
{
end += len;
begin = end;
found.clear(); //清空
found.resize(LLen,0);
count = 0;
}else
{
found[pos[end]]++;
if(found[pos[end]]<=needed[pos[end]])
count++;   //统计cnt

if((end-begin)/len+1==LLen)
{
if(count==LLen)   //valid window
res.push_back(begin);

if(found[pos[begin]]<=needed[pos[begin]])
count--;
found[pos[begin]]--;
begin+=len;
}
end+=len;
}
}
}

return res;

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: