#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void get_next(char T[100],int *next);
int Index_KMP(char S[100],char T[100],int pos);
int main()
{
int n;
char S[100],T[100];
gets(S);//直接用字符串决定了字符数组从0开始而非1
gets(T);
n=Index_KMP(S,T,2);
printf("%d",n);
return 0;
}
void get_next(char T[100],int *next)
{
int j,i;
int t;
next[0]=-1;//因为next函数定义中当j==1时,next[j]==0
j=-1;
i=0;
t=strlen(T);
while(i<t)
{
if(j==-1||T[j]==T[i])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int Index_KMP(char S[100],char T[100],int pos)
{
int i,j;
int s,t;
i=pos;
j=0;
int next[100];
get_next(T,next);
s=strlen(S);
t=strlen(T);
while(i<s&&j<t)//因为j为下标所以当j等于长度的时候就说明匹配成功了。
{
if(j==-1||S[i]==T[j])
{
j++;
i++;
}
else
j=next[j];
}
if(j>=t)
{
return (i-t+1);//因为要找的是子串在主串上的位置,所以应从下标的基础上加一。
}
else
return 0;
}
这里用字符串而不是串结构演示的KMP模式匹配算法,所以在比较大小,next数组的头元素等处有变化,但是算法是一样的,具体变化见代码。
学后感。。
《大话数据结构》上本节罗列了很多例子,原理和没讲没啥区别,本小白智商比较低,看得一脸懵逼,学了好久才勉强算懂了。
对于《大话数据结构》它的优点大家都知道,就不说了,个人感觉里面的废话太多,很多地方都只是罗列例子,算法怎么来的,或者这个算法的原理感觉讲的比较坑。