KMP算法
void preKMP(const char *const pSub,char *const pIndex) {//KMP索引计算方法int intIndex=-1;//无法找到相同的字符的索引
pIndex=intIndex;//第一个默认为找不到的
for (size_t i=1;i<strlen(pSub);++i)//遍历所有子串,从第二个字符开始遍历
{
//找不到的情况下
while(intIndex>-1 && pSub!=pSub)
intIndex=pIndex;
//找到的情况下进行索引纠正
if(pSub==pSub)
++intIndex;//找到的情况进行索引进行赋值
//最后确定索引
pIndex=intIndex;
}
}
void KMP(const char *const pStr,const char *const pSub)
{
char *arrIndex=new char;//先分配一个索引数组与子字符串对应
preKMP(pSub,arrIndex);//准备好数组索引
size_t intIndex=arrIndex;
for (size_t i=0;i<strlen(pStr);++i)
{
while(intIndex>-1 && pSub!=pStr)
intIndex=arrIndex;
if(pSub==pStr)
intIndex++;
if (intIndex==strlen(pSub)-1)
{
intIndex=arrIndex;
printf("..............\n");
}
}
delete[] arrIndex;
}
页:
[1]