思路就是
比如 我的关键词为 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);
}