BF核心思想: S是主串,T是字串。比较连个字符串S和T,先比较S[ 1 ] 和T[ 1 ]进行比较,如果相等则比较S[ 2 ]和T[ 2 ],一直移动到S[ N ]为止,若S[ 1 ]和T[ 1 ]不相等,则S享向右动一个字符,再将S[ 2 ]和T[ 1 ]进行比较。
KMP算法:
next数组基本原理:
比如说我们现在算第七位字符的next数组值,我们就需要找他的前一位,也就是第六位,看第六位的next值表示的序号,看此序号中的字符是否和第六位相等,
如果相等,则第七位next的值为第六位next的值+1,
如果不相等,就要继续按照next数组的值向前找,如果找到,就输出此时的next值+1,如果一直到T【1】都没找到,就输出此时next值+1
#include <stdio.h>
typedef char* String;
void get_next(String T, int *next)
{
int j = 0;
int i = 0;
next[ 1 ] = 0;
while(i < T[ 0 ] )
{
if( 0 == j || T[ i ] == T[ j ] )
{
i++;
j++;
next[i] = j;
if( T[i] != T[j] )
{
next[i] = j;
}
else
{
next[i] = next[j];
}
}
else
{
j = next[j];
}
}
}
int main()
{
char str[255] = " ababaaaba";
int next[255];
int i = 1;
str[0] = 9;
get_next(str , next);
for(i = 1;i <10; i++)
{
printf("%d",next[ i ] );
}
}
//返回子串T在主串S的第pos个字符之后的位
//若不存在,则返回0
int Index_KMP( Strint S, String T , int pos )
{
int i = pos;
int j = 1;
int next[255];
get_next( T , next);
while( i <= S[0] && j <= T[0] )
{
if( 0 == j || S[ i ] == T[ i ] )
{
i++;
j++;
}
else
{
j = next[j];
}
}
if( j > T[ 0 ] )
{
return i - T[ 0 ];
}
else
{
return 0;
}
}