void KMP_prefix( const char *t, int *
next )
{
int len = strlen(t) ;
int i, j = -1 ;
next[0] = -1 ;
//请读者自行思考i什么时候增长
for( i=1; i<len; ++ i )
{
// i永远和j+1位的比较(因为j初始值为-1)
//如果失配就执行跳转。直到j为-1为止。
while( (j+1>0)&&(t[j+1]!= t[i]) )
j = next[j] ;
//如果匹配,则两个串的指针都增长
if( t[j+1]== t[i] )
++ j ;
// 这句很抽象,意思是:
// 跳转的位置永远是匹配成功的下一位
//也是唯一给跳转表赋值的一句
next[i] = j+1 ;
}
}
//主函数:可以看出这个函数与上面的函数极其相似
int KMP_matcher( const char *s, const char *t, int beg )
{
int l1 = strlen(s), l2 = strlen(t) ;
int *next = new int [l2] ;
KMP_prefix( t, next ) ;
int i, j = -1, ans = beg ;
for( i=beg; i<l1; ++ i )
{
while( (j+1>0)&&(t[j+1]!= s[i]) )
{
j = next[j] ;
}
if( t[j+1]== s[i] )
{
++ j ;
}
if( j+1== l2 )
{
ans = i-l2+1 ;
break ;
}
}
return ans ;
}
{
int len = strlen(t) ;
int i, j = -1 ;
next[0] = -1 ;
//请读者自行思考i什么时候增长
for( i=1; i<len; ++ i )
{
// i永远和j+1位的比较(因为j初始值为-1)
//如果失配就执行跳转。直到j为-1为止。
while( (j+1>0)&&(t[j+1]!= t[i]) )
j = next[j] ;
//如果匹配,则两个串的指针都增长
if( t[j+1]== t[i] )
++ j ;
// 这句很抽象,意思是:
// 跳转的位置永远是匹配成功的下一位
//也是唯一给跳转表赋值的一句
next[i] = j+1 ;
}
}
//主函数:可以看出这个函数与上面的函数极其相似
int KMP_matcher( const char *s, const char *t, int beg )
{
int l1 = strlen(s), l2 = strlen(t) ;
int *next = new int [l2] ;
KMP_prefix( t, next ) ;
int i, j = -1, ans = beg ;
for( i=beg; i<l1; ++ i )
{
while( (j+1>0)&&(t[j+1]!= s[i]) )
{
j = next[j] ;
}
if( t[j+1]== s[i] )
{
++ j ;
}
if( j+1== l2 )
{
ans = i-l2+1 ;
break ;
}
}
return ans ;
}