您的位置:首页 > 其它

KMP模式匹配算法

2014-09-07 10:37 134 查看
#include <stdio.h>
#include<stdlib.h>
#include <ctype.h>

typedef unsigned char u8;

void get_next(u8 *T,int *next)
{
int i,j;
i = 1;
j = 0;
next[1] = 0;
while( i < T[0])
{
if( j == 0 || T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}

int Index_KMP( u8 *S, u8 *T, int pos)
{
int i = pos;
int j = 1;
int next[255];
get_next( T, next);
while( i <= S[0] && j <= T[0])
{
if( j == 0 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if( j > T[0])
return i - T[0];
else
return 0;
}

int main(int argc, char *argv[])
{
u8 s[] = " abacdaaabcdesiosjdifiejfi";
u8 t[] = " cdesios";

s[0] = sizeof(s) - 2;
t[0] = sizeof(t) - 2;

//	for( i = 0; i < j; i++)
printf("%d",Index_KMP( s, t, 1));
while(1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: