编程之美 最短摘要生成

来源:互联网 发布:手机红外热像仪软件 编辑:程序博客网 时间:2024/05/01 16:46

本来以为这个会很难的,因为自己不是很了解这方面的东西。

看了下解释 大致明白了,就是用最少的句子 ,包含所有的关键词

ok~看了编程之美的code后 感觉很好,类似kmp算法,跳过已经比对过的字符串,然后向后移动。


思路就是 

比如 我的关键词为 bottom  bot 

我的句子  hello  are  you bottom of do the is bot doke astring

在一个句子里面找到包含关键词的 最短的句子。当然 关键词可以无序排列。

编程之美的思路 就是

设置一个begin 一个end 起初都指向句子头

end向后移动一直到包含所有关键词 停止。

记录长度,同时移动begin,直至不包含某关键词后,再次移动end,直至包含。

总结来说  就是 一遍获得所有结果。


#include <iostream>#include<cstdio>#include<set>#include<string>#include<vector>using namespace std;bool isMatchAll(vector<string>& sentence,set<string>& keys,int begin,int end){    int cnt=0;    int keySize=keys.size();    for(int i=begin;i<=end;i++){        if(keys.count(sentence[i])){            cnt++;        }    }    if(cnt==keySize)        return true;    return false;}void find(vector<string>& sentence,set<string>&keys){    int begin=0,end=0;    int mbegin=0,mend=0;    int minDist=INT_MAX;    while(true){        while(!isMatchAll(sentence,keys,begin,end)){            end++;            if(end>=sentence.size()-1){                break;        }        }        while(isMatchAll(sentence,keys,begin,end)){            if(end-begin+1<minDist){                mbegin=begin;                mend=end;                minDist=end-begin+1;            }            begin++;        }        if(end>=sentence.size()-1){            break;        }    }    cout<<"minDist="<<minDist<<endl;    for(;mbegin<=mend;mbegin++){        cout<<sentence[mbegin]<<" ";    }}int main() {    freopen("a.txt","r",stdin);    vector<string> sentence;    string str;    while(cin>>str){        sentence.push_back(str);    }    set<string> keys;    keys.insert("bottom");    keys.insert("bot");    find(sentence,keys);    return 0;}

结果为:

minDist=6
bottom of do the is bot


0 0
原创粉丝点击