主题:贴个KMP算法的程序
我看置顶的算法篇中没有KMP的实现,就写了个.KMP的解释网上多得很,我就不说了
------------------------------------------------------------------------
#include <stdio.h>
int fastfind(char* s,int s_len,char* p,int p_len,int* f);/*KMP算法的实现*/
void fail(int* f,int f_len,char* ch);/*失效位置数组的填写*/
int main()
{
char* s = "abcaabaa";
char* p = "aba";
int f[3] ={0};
fail(f,3,p);
printf("%d\n",fastfind(s,8,p,3,f));
return 0;
}
int fastfind(char* s,int s_len,char* p,int p_len,int* f)//s是串,p是子串,f是失效函数数组
{
int posP = 0,posS = 0;
while(posP < p_len&&posS < s_len)
if(p[posP]==s[posS]){posP++;posS++;}
else
if(posP == 0) posS++;
else posP = f[posP-1]+1;
if(posP < p_len)
return -1;/*匹配失败*/
else
return posS - p_len;
}
void fail(int* f,int f_len,char* ch)
{
int i,j;
f[0] = -1;
for(j = 1;j<f_len;j++)
{
i = f[j-1];
while((*(ch+j+1)!=*(ch+i+1))&&i>=0)i=f[i];
if(*(ch+j+1)==*(ch+i+1))
f[j] = i+1;
else
f[j] = -1;
}
}
------------------------------------------------------------------------
#include <stdio.h>
int fastfind(char* s,int s_len,char* p,int p_len,int* f);/*KMP算法的实现*/
void fail(int* f,int f_len,char* ch);/*失效位置数组的填写*/
int main()
{
char* s = "abcaabaa";
char* p = "aba";
int f[3] ={0};
fail(f,3,p);
printf("%d\n",fastfind(s,8,p,3,f));
return 0;
}
int fastfind(char* s,int s_len,char* p,int p_len,int* f)//s是串,p是子串,f是失效函数数组
{
int posP = 0,posS = 0;
while(posP < p_len&&posS < s_len)
if(p[posP]==s[posS]){posP++;posS++;}
else
if(posP == 0) posS++;
else posP = f[posP-1]+1;
if(posP < p_len)
return -1;/*匹配失败*/
else
return posS - p_len;
}
void fail(int* f,int f_len,char* ch)
{
int i,j;
f[0] = -1;
for(j = 1;j<f_len;j++)
{
i = f[j-1];
while((*(ch+j+1)!=*(ch+i+1))&&i>=0)i=f[i];
if(*(ch+j+1)==*(ch+i+1))
f[j] = i+1;
else
f[j] = -1;
}
}