小七技术论坛,计算机安全和杀毒软件,编程交流于软件安全技术交流,给新手一个绿色安全的论坛

标题: KMP算法 [打印本页]

作者: x7code    时间: 2011-12-26 13:33
标题: KMP算法
void preKMP(const char *const pSub,char *const pIndex) {//KMP索引计算方法
int intIndex=-1;//无法找到相同的字符的索引
pIndex[0]=intIndex;//第一个默认为找不到的
for (size_t i=1;i<strlen(pSub);++i)//遍历所有子串,从第二个字符开始遍历
{
//找不到的情况下
while(intIndex>-1 && pSub[intIndex+1]!=pSub[i])
intIndex=pIndex[intIndex];
//找到的情况下进行索引纠正
if(pSub[intIndex+1]==pSub[i])
++intIndex;//找到的情况进行索引进行赋值
//最后确定索引
pIndex[i]=intIndex;

}
}
void KMP(const char *const pStr,const char *const pSub)
{
char *arrIndex=new char[strlen(pSub)*sizeof(char)];//先分配一个索引数组与子字符串对应
preKMP(pSub,arrIndex);//准备好数组索引
size_t intIndex=arrIndex[0];
for (size_t i=0;i<strlen(pStr);++i)
{
while(intIndex>-1 && pSub[intIndex+1]!=pStr[i])
intIndex=arrIndex[intIndex];
if(pSub[intIndex+1]==pStr[i])
intIndex++;
if (intIndex==strlen(pSub)-1)
{
intIndex=arrIndex[intIndex];
printf("..............\n");
}
}
delete[] arrIndex;
}







欢迎光临 小七技术论坛,计算机安全和杀毒软件,编程交流于软件安全技术交流,给新手一个绿色安全的论坛 (https://xqmsyk.com/) Powered by Discuz! X3.3