快速匹配算法(KMP) ,核心之处在于:
主串指针不用回溯,直接前进!!!
关键之处在于: NEXT[i]的值的求法,KMP算法其实很简洁的!!!
主串指针不用回溯,直接前进!!!
关键之处在于: NEXT[i]的值的求法,KMP算法其实很简洁的!!!
==================================================================
/* KMP algorithms for string comparse...*/
#include <stdio.h>
#include <string.h>
#define MAX 101
void get_next ( int next[],char s2[],int l2)/* 求NEXT的值*/
{
int i=1 ,j=0 ;
next[1] = 0 ;
for( ; i < l2 ; )
{
if ( j== 0 || s2[i] == s2[j] )
{
++i ;
++j ;
if ( s2[i] != s2[j])
next[i] = j ;
else
next[i] = next[j] ;
}
else
j = next[j] ;
}
}
int compares(char s1[],char s2[] ,int l1, int l2,int next[],int start)/*匹配算法*/
{
int i=start ,j=1 ;
for( ; i <= l1 && j <= l2; )
{
if ( j == 0 || s1[i] == s2[j] )
{
++ i ;
++ j ;
}
else
j = next[j] ;
}
if ( j > l2 )
return (i-l2) ;
else
return 0 ;
}
int main(void)
{
char c,s1[MAX]={'\0'},s2[MAX]={'\0'};
int i,j,k,l1=0,l2=0,start;
int next[MAX] ={0} ;
for(; (c = getchar())!= ' '; )
{
s1[++l1] = c ;
}
for(; (c = getchar() ) != '\n' ; )
{
s2[++l2] = c ;
}
printf("Please input where are you want to comparse: ");
scanf("%d",&start);
get_next(next,s2,l2);
printf("====result come out ==========\n");
k = compares(s1,s2,l1,l2,next,k) ;
if ( k )
printf("OK!!!,S2 in S1's place is : %d\n",k);
else
printf("NOT OK!!!\n");
system("pause");
return 0 ;
}