从一个长字符串中查找包含给定字符集合的最短子串。例如,长串为“aaaaaaaaaacbebbbbbdddddd
dcccccc”,字符集为{abcd},那么最短子串是“acbebbbbbd”。如果将条件改为“包含且只包含给定字符集合”,你的算法和实现又将如何改动。
#include <map>
#include <set>
#include <string>
#include <iostream>
using namespace std;
bool is_all_included(map<char,int>& keywords_count_map){
for(map<char,int>::iterator it =keywords_count_map.begin(); it != keywords_count_map.end();++it){
if(0 == it->second){
return false;
}
}
return true;
}
string shortest_abstract(string text, const set<char>& keywords){
map<char,int> keywords_count_map;
for(set<char>::iterator it = keywords.begin(); it != keywords.end(); ++it){
keywords_count_map[*it] = 0;
}
int length =text.length();
int shortest_length = length;
int begin =0, end = 0;
int abstract_begin = -1, abstract_end = -1;
for(;;){
while(!is_all_included(keywords_count_map) && end < length){
char key = text.at(end);
if(keywords_count_map.find(key) != keywords_count_map.end()){
keywords_count_map[key] += 1;
}
++end;
}
while(is_all_included(keywords_count_map)){
if(end - begin < shortest_length){
shortest_length = end - begin;
abstract_begin = begin;
abstract_end = end;
}
char key = text.at(begin);
if(keywords_count_map.find(key) != keywords_count_map.end()){
keywords_count_map[key] -= 1;
}
++begin;
}
if(end >= length){
break;
}
}
if(abstract_begin >=0 && abstract_end >=0){
return text.substr(abstract_begin,abstract_end-abstract_begin);
}
return string("-1");
}
int main(){
string text= "aaaaaaaaaacbebbbbbdddddddcccccc";
set<char> s;
s.insert('a');
s.insert('b');
s.insert('c');
s.insert('d');
string o =shortest_abstract(text,s);
cout << o << endl;
return-1;
}