编程之美 --- 最短摘要生成

本文介绍了一种用于从给定字符串中查找包含特定字符集的最短子串的算法。该算法通过移动窗口的方式高效地解决问题,避免了不必要的回溯操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


思路就是 

比如 我的关键词为 abde

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

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

编程之美的思路 就是

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

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

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

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



#include <stdio.h>
#include <iostream>
using namespace std;

const int MAXLEN = 256;

//if the str string includes all the pattern 
bool isWholeMatched(char str[], int begin, int end,char pstr[])
{
    int i = 0;
	bool hashtable[MAXLEN];
    int plen = strlen(pstr);

	for (i = 0; i < MAXLEN; i++)
        hashtable[i] = false;
	for (i = begin; i <= end; i++)
	{
		hashtable[str[i]] = true;
	}
	for (i = 0; i < plen;  i++)
	{
		if (!hashtable[pstr[i]])
			return false;
	}
	return true;

}

void findStr(char srcstr[], char pstr[])
{

	int i = 0;

	int begin, end, srclen, minbegin, minend, minlen;
	begin = end = 0;
	srclen = strlen(srcstr);
	minlen = 65535;
    
	while (end < srclen)
	{
		while (!isWholeMatched(srcstr, begin, end, pstr) && end < srclen)
		{
			end++;
		}
        while (end < srclen && begin < end && isWhileMatched(srcstr, begin, end, pstr))
		{
			begin++;
		}

		if (minlen > (end - begin + 1))
		{
			minbegin = begin - 1;
			minend = end;
			minlen = minend - minbegin + 2;
		}
	}
	if (minlen != 0xffff)
	{
		cout<<"output the shorest abstract:\n";
		for (i = minbegin; i <= minend; i++)
			cout <<srcstr[i];
	}


}

void main(void)
{
	char pstr[] = "abcd";
	char srcstr[] = "I'm a big cow boy. do abcd think so?";
	findStr(srcstr, pstr);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值