#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string.h>
#define MAXLEN 255
#define OK 1
#define ERROR 0
#define Status int
#define SElemType char
#include<stdlib.h>
using namespace std;
//----串的顺序存储结构----//
typedef struct
{
char ch[MAXLEN+1];
int length;
}SString;
//计算串T的next函数值
void get_next(SString T,int next[])
{
//求模式串T的next函数修正值并存入数组next
T.length=strlen(T.ch);
int i,j;
i=0;
next[0]=-1;
j=-1;
while(i<T.length-1)
{
if(j==-1||T.ch[i]==T.ch[j])
{
++i;
++j;
if(T.ch[i]!=T.ch[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
//for(int k=0;k<T.length;k++)
//printf("%d ",next[k]);
}
//KMP算法
int Index_KMP(SString S,SString T,int pos)
{
//利用模式串T的next函数求T在主串S中第pos个字符之后的位置
//其中,T非空,0<=pos<=S.length-1
int i,j;
int next[MAXLEN+1];
for(int k=0;k<=T.length;k++)
next[k]=0;
S.length=strlen(S.ch);
T.length=strlen(T.ch);
i=pos-1;j=0;
get_next(T,next);
while(i<=S.length-1&&j<=T.length-1) //两个串均未比较到串尾
{
if(j==-1||S.ch[i]==T.ch[j])
{
++i;
++j;
}
else
j=next[j];
}
if(j>T.length-1)
return i-T.length;
else
return -1;
}
//实现
int main()
{
SString S,T;
int p;
//输入串S,T
printf("输入母串S\n");
scanf("%s",S.ch);
printf("输入子串T\n");
scanf("%s",T.ch);
printf("输入从第p个字符开始匹配,p=\n");
scanf("%d",&p);
//T.length=strlen(T.ch);
//get_next(T,next);
printf("从第%d位开始匹配\n",Index_KMP(S,T,p)+1);
return 0;
}
//httphkighttkjjddhttujdjhhjtt
//acabaabaabcacaabc
//abaabcac
题目:用KMP算法实现串操作的模式匹配算法
代码: