一个字符串,查找字符串列表中,合并后的字串位置
1:遍历方法
2.优化后的遍历
void findSubString(string &s, string* words, int len)
{
if(len == 0)
{
return;
}
int n = s.length();
int word_cnt = len;
int m = words[0].length();
map<string, int> words_dict;
for(int i=0; i <len; ++i)
{
int &count = words_dict[words[i]];
count += 1;
}
vector<int> ret;
for(int i=0; i < n; ++i)
{
map<string, int> cur_dict;
int matched = 0;
for(int start =i; start < n; start +=m)
{
string w = s.substr(start, m);
printf("w:%s \n", w.c_str());
map<string, int>::iterator it = words_dict.find(w);
int &cur_dict_count = cur_dict[w];
if(it != words_dict.end() && cur_dict_count < it->second)
{
cur_dict_count += 1;
matched += 1;
}
else
{
break;
}
// all words matched
if(matched == word_cnt)
{
ret.push_back(i);
break;
}
}
}
for(int i=0; i < ret.size(); ++i)
{
printf("%d ", ret[i]);
}
}
void findSubString2(string &s, string* words, int len)
{
if(len == 0)
{
return;
}
int n = s.length();
int word_cnt = len;
int m = words[0].length();
map<string, int> words_dict;
for(int i=0; i <len; ++i)
{
int &count = words_dict[words[i]];
count += 1;
}
vector<int> ret;
//鍙亶鍘?-m
for(int i=0; i < m; ++i)
{
map<string, int> cur_dict;
int l =i;//l,r琛ㄧず褰撳墠鐨勫尯闂翠袱渚х鐐?
int matched = 0;
for(int r =i; r < n; r+=m)
{
//鑾峰彇褰撳墠鐨勫崟璇?
string word = s.substr(r, m);
map<string, int>::iterator it = words_dict.find(word);
//濡傛灉鍗曡瘝涓嶅湪璇嶅簱閲岋紝娓呯┖涔嬪墠鐨勬暟鎹?
if(it == words_dict.end())
{
//l璧嬪€兼垚涓嬩竴涓紑濮嬬殑r
l = r+m;
//鎵€鏈夊尮閰嶈褰曟竻绌?
matched = 0;
cur_dict.clear();
continue;
}
int &cur_dict_count = cur_dict[word];
cur_dict_count += 1;
matched += 1;
//濡傛灉鏁伴噺瓒呯晫鐨勮瘽锛屽氨寮瑰嚭宸︿晶
while(cur_dict[word] > words_dict[word])
{
string w = w.substr(l, m);
int &cur_dict_count = cur_dict[w];
cur_dict_count -= 1;
matched -= 1;
l += m;
}
if(matched == word_cnt)
{
ret.push_back(l);
}
}
}
for(int i=0; i < ret.size(); ++i)
{
printf("%d ", ret[i]);
}
}
int main()
{
string s = "barfoothefoobarman";
string words[] = {"foo", "bar"};
findSubString2(s, words, 2);
return 0;
}