#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>
#define MAX 256
void getNext(const char * t,int * Next)//get the Next array
{
int k=-1;
int j=0;
int size=strlen(t);
Next[0]=-1;
while(j<size)
{
if(k==-1||t[j]==t[k])//if k==-1 there are two conditions
//one is this is the first time entering the loop
{ //if t[j]==t[k] get the next[j+1] directly
k++;//the other is the end of the iteration cos k==-1;
j++;
Next[j]=k;//whatever Next[j]=k
}
else
k=Next[k];
}
}
int kmp(const char * Dest,const char *subStr)//find the starting position of the sub
{ //in the Dest through KMP
int destSize=strlen(Dest);
int subSize=strlen(subStr);
int i,j;
int Next[MAX];
i=j=0;
assert((Dest!=NULL)&&(subStr!=NULL));
getNext(subStr,Next);
while(i<destSize&&j<subSize)
{
if(j==-1||Dest[i]==subStr[j])//if j==-1 the main string need match the next elements
{ //and the subString begin from the beginning
i++; //if Dest[i]==subStr[j] both string need shift to the
j++; // next elements
}
else
j=Next[j]; //if match fail,glide back to Next[j]
}
if(j==subSize)return i-j;
return -1;
}
int main()
{
char Dest[]="ssdfdsskdjfkds";//to store the substring to be matched
char sub[]="fffff";
printf("the starting position is :%d\n",kmp(Dest,sub));//get the starting position
getchar();
getchar();
return 0;
}
分享到:
相关推荐
kmp算法--VC6.0
基于C#实现并对比三种基本的字符串匹配算法-RK算法-KMP算法-朴素算法
kmp算法 kmp算法_基于Java实现的kmp算法
kmp算法 kmp算法_基于Python+kmp算法实现模糊文本字符串匹配
kmp算法kmp-algorithm-master.zip
kmp算法 kmp算法_基于C语言实现的kmp模式匹配算法
DS串应用--KMP算法DS串应用--KMP算法DS串应用--KMP算法DS串应用--KMP算法
kmp算法 KMP算法是什么? 引用自百度百科: KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配...
算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP算法 KMP
kMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法JavakMP算法Java...
模式匹配的一种改进算法----KMP算法
KMP算法
KMP算法的板子
kmp算法,kmp-algorithm-master (1).zip
KMP算法详解KMP算法详解KMP算法详解KMP算法详解
KMP算法详解KMP算法详解KMP算法详解KMP算法详解KMP算法详解
acm编程算法-kmp算法论文 基本的字符串匹配算法,有扩展
首先,字符串"BBC ABCDAB ABCDABCDABDE"的第一个字符与搜索词"ABCDABD"的第一个字符,进行比较。KMP算法的想法是,设法利用这个已知
KMP算法,Martix67大神blog精华剪辑PDF版
模式匹配,KMP算法,string-match-kmp-master.zip