您的位置:首页 > 其它

kmp算法的实现,严蔚敏版本(调试成功)

2009-09-15 15:52 246 查看
学数据结构时看书算法编的
kmp算法的实现,严蔚敏版本(调试成功)

code:

/************/

main.cpp

#include "stdio.h"
#include "setting.h"

void main()
{
int pos,result,count;
SString S,T;
char *p,*q;

p = S;
q = T;
count=1;

printf( "请输入主串S:" );
scanf("%s",p);

printf( "请输入模串T:" );
scanf("%s",q);

printf( "请输入S中第一个进行匹配的字符的位置pos:" );
scanf( "%d",&pos );

result = Index_KMP( S,T,pos,count );

if( result == 0 )
printf( "匹配不成功!/n" );
else
printf( "匹配成功,相匹配的位置是:%d/n",result );

printf( "总共经过%d次匹配/n",count );
}

/********************/

kmp_operation.cpp

#include "setting.h"

int Index_KMP( SString S,SString T,int pos ,int &count)
{
int i,j,Len_s,Len_t;
int next[256];

i = pos;
j = 1;

Len_s = StrLength( S );
Len_t = StrLength( T );

get_next( T,next );

while( i <= Len_s && j <= Len_t )
{
if( j == 0 || S[i - 1] == T[j - 1] )
{
i++;
j++;
}
else
{
j = next[j];
count++;
}
}

if( j > Len_t)
return i - Len_t;
else
return 0;
}

void get_next( SString T,Next next )
{
int i,j,Len_t;

i = 1;
j = 0;
next[1] = 0;

Len_t = StrLength( T );

while( i < Len_t )
{
if( j == 0 || T[i - 1] == T[j - 1] )
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}

status StrLength( SString S )
{
int i;
i = 0;

while( *(S + i) != '/0' )
{
i++;
}

return i;
}

/*************************/

setting.h

#define MAXSTRLEN 255

typedef int status;
typedef char SString[MAXSTRLEN + 1];
typedef int Next[MAXSTRLEN + 1];

int Index_KMP( SString ,SString ,int ,int & );

void get_next( SString ,Next );

status StrLength( SString S );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐