编程之美 最短摘要生成

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

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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值