KMP模式匹配算法可在O(n+m)的时间数量级上完成串的模式匹配算法。
定义数据结构SString,其中第一个单元用于存放串的长度。
// KMP.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAXSTRLEN 40
typedef char SString[MAXSTRLEN+1];
bool StrAssign(SString str, char* chars)
{
if (strlen(chars)>MAXSTRLEN)
{
return false;
}
else
{
str[0]=strlen(chars);
for (int i=1;i<=str[0];i++)
{
str[i]=chars[i-1];
}
return true;
}
}
void get_nextval(SString subStr,int nextval[])
{
int i=1,j=0;
nextval[1]=0;
while (i<subStr[0])
{
if (j==0 || subStr[i]==subStr[j])
{
++i;
++j;
if (subStr[i]!=subStr[j])
{
nextval[i]=j;
}
else
nextval[i]=nextval[j];
}
else
j=nextval[j];
}
}
int Index_KMP(SString str, SString subStr, int pos, int next[])
{
int i=pos,j=0;
while (i<=str[0] && j<=subStr[0])
{
if (j==0 || str[i]==subStr[j])
{
++i;
++j;
}
else
j=next[j];
}
if (j>subStr[0])
{
return i-subStr[0];
}
else return 0;
}
int main(int argc, char* argv[])
{
SString str, subStr;
StrAssign(str,"aaabaaaab");
StrAssign(subStr,"aaaab");
int i=subStr[0];
int *p=(int*)malloc((i+1)*sizeof(int));
get_nextval(subStr,p);
printf("子串的nextval函数为:");
for (int j=1;j<=i;j++)
{
printf("%d ",p[j]);
}
printf("\n");
printf("主串和子串在第%d个字符处首次匹配\n", Index_KMP(str,subStr,1,p));
return 0;
}