在网上搜索KMP算法的代码实现的时候,出现的结果总是不满意,关于next数组以及nextval数组的实现也少,即使搜到了也感觉不是很好,所以自己花一下午时间自己写了一个自认为比较完美的KMP算法的C语言实现。
本文章的代码是可以直接运行的代码!
头文件:head.h
#ifndef _KMP_
#define _KMP_
#include <stdio.h>
#include <string.h>
#define MAXLEN 255
typedef struct
{
char ch[MAXLEN];
int length;
} SString;
#endif
KMP算法、求next数组、nextval数组:func.c
#include "head.h"
//得到next数组
void get_next(SString T, int next[])
{
next[1] = 0;//next[1] is always '0'
if(T.length<2)
return;
next[2] = 1;//next[2] is always '1'
if(T.length<3)
return;
int i = 3;
int j=0, k=0;
int head=0, tail=0, cnt=0, flag=0;
while (i <= T.length) {
cnt = 0;
flag = 1;
for(j=1; j< i-1; j++)
{
head = 1;
tail = i-j;
for(k=1; k<=j; k++)
{
if(T.ch[tail++] != T.ch[head++]){
flag=0;
break;
}
}
if(flag && cnt<j)
cnt = j;
}
next[i++] = cnt+1;
}
}
//将next数组优化为nextval数组
void get_nextval(int nextval[], int next[], SString T)
{
nextval[1] = 0;
for(int j=2; j<=T.length; j++)
{
if(T.ch[next[j]] == T.ch[j])
nextval[j] = nextval[next[j]];
else
nextval[j] = next[j];
}
}
//使用nextval数组查找
int IndexKMP(SString S, SString T)
{
int next[T.length + 1];
int nextval[T.length+1];
get_next(T, next);
get_nextval(nextval, next, T);
//show
printf("\npattern:");
for(int i = 1; i < T.length+1; i++)
printf("%c ", T.ch[i]);
printf("\nnext :");
for(int i = 1; i < T.length+1; i++)
printf("%d ", next[i]);
printf("\nnextval:");
for(int i = 1; i < T.length+1; i++)
printf("%d ", nextval[i]);
int i = 1, j = 1;
while (i <= S.length && j <= T.length) {
if (j == 0 || S.ch[i] == T.ch[j]) {
++i; ++j;
} else
j = nextval[j];
}
if (j > T.length)
return i - T.length; //match success
else
return 0;//match failed
}
主函数:KMP.c
#include "head.h"
#include "func.c"
int main(int argc, char **argv)
{
SString s,t;
strcpy(&s.ch[1], argv[1]);
s.length = strlen(argv[1]);
strcpy(&t.ch[1], argv[2]);
t.length = strlen(argv[2]);
printf("%s's size:%d\n", &s.ch[1], s.length);
printf("%s's size:%d\n", &t.ch[1], t.length);
printf("\n\n%s first appeared at:%d\n", &t.ch[1], IndexKMP(s, t));
return 0;
}
编译运行结果:
第一次发博客,代码哪里有错误或者可以改进可以私信我,谢谢啦!