kmp算法是一种改进的字符串匹配算法,KMP算法的关键是根据给定的模式串T,定义一个next函数。next函数包含了模式串本身局部匹配的信息。
头文件KmpAlgorithm.h
#ifndef KMPALGORITHM_H
#define KMPALGORITHM_H
void Get_next(char *T,int *next);
int Index_Kmp(char *s,char *T,int pos);
#endif //KMPALGORITHM_H
实现文件KmpAlgorithm.cpp
#include "KmpAlgorithm.h"
#include <string.h>
void Get_next(char *T,int *next) //求模式串T的next函数
{
int i,j;
i = 0;
j = -1;
next[0] = -1;
while(T[i] != '\0') //T串没有结束就循环
{
if(j == -1 || T[j] == T[i]) //T[i]表示后缀的单个字符,T[j]表示前缀的单个字符
{
++i;
++j;
next[i] = j;
}
else
j = next[j]; //若字符不相同,则回溯
}
}
int Index_Kmp(char *s,char *t,int pos) //pos不为零,则是从主串的第pos个字符开始匹配
{
int i = pos - 1; //数组下标是从零开始的
int j = 0;
int next[255];
Get_next(t,next);
while(s[i] != '\0' && t[j] != '\0')
{
if(j == -1 || s[i] == t[j]) //两个字符相等则继续比较,j == -1是在回溯时产生的,因为next[0]
{ //回溯到j == -1,不在字符数组内
++i;
++j;
}
else
j = next[j]; //不相等则回溯
}
if(t[j] == '\0') //如果相等返回在主串中的位置
return i - strlen(t) + 1;
else
return -1;
}
测试文件main.cpp
#include "KmpAlgorithm.h"
#include <stdio.h>
#include <string.h>
int main()
{
char s[255],t[255];
int pos = 0;
int position = 0;
memset(s,0,sizeof(char)*255);
memset(t,0,sizeof(char)*255);
printf("请输入主串的内容:\n");
scanf("%s",s);
printf("请输入子串的内容:\n");
scanf("%s",t);
printf("请输入从主串的第几个字符开始匹配:\n");
scanf("%d",&pos);
position = Index_Kmp(s,t,pos);
if(position == -1)
printf("子串没有在主串中出现");
else
printf("子串在主串的第%d个位置出现\n",position);
return 0;
}