字符串的模式匹配,KMP算法

来源:互联网 发布:怎么报考网络教育 编辑:程序博客网 时间:2024/05/17 07:43

KMP算法是模式匹配的一种改进的算法,所谓的模式匹配也就是对于两个字符串主串S和模式串T。从主串的S的pos个字符起和模式串中的第一个字符进行比较,如果相等,则继续比较后面的字符,否则从主串的下一个字符重新和模式串 中的字符进行比较,依次类推直到模式T中的每一个字符依次和主串中的S中的一个连续的字符序列相等,我们成为是匹配成功。KMP算法能够提高匹配的效率,当一趟匹配过程中出现主串和模式串中的字符不相等的时候,不需要回溯指针,而是利用已经匹配的部分的结果将模式向右滑动尽可能远的一段距离后继续进行比较。

#include<iostream>
#include<conio.h>
using namespace std;
#define MAXSTRLEN 255
typedef char SString[MAXSTRLEN+1];
int next[MAXSTRLEN];//next[]成为去全局变量
int nextval[MAXSTRLEN];//nextval[]成为全局变量
void get_next(SString T)
{
int i=1,j=0;
next[1]=0;
while(i<T[0])
{
if(j==0 || T[i]==T[j])
{
++i;
++j;
next[i]=j;
}
else
{
j=next[j];
}
}


}
int strlen(SString S)
{
int i=1;
while(S[i]!='\0')
i++;
return i;
}
int Index_KMP(SString S,SString T,int pos)
{
int i=pos,j=1;
while(i<S[0] && j<=T[0])
{
if(j==0 || S[i]==T[j])
{
++i;++j;
}
else
j=next[j];
}
if(j>T[0])
return i-T[0];
else
return 0;
}
int main()
{
     SString S,T;
cout<<"input the main String S\n";
gets(S+1);
S[0]=strlen(S)-1;
cout<<"input the model String T\n";
gets(T+1);
T[0]=strlen(T)-1;
     char choice;
int j=1,i;
while(j)
{
cout<<"***********"<<endl;
cout<<"******模式匹配**********"<<endl;
cout<<"******1.计算next(T)*******"<<endl;
cout<<"******2.KMP算法匹配*******"<<endl;
cout<<"请输入你的选择:";
cin>>choice;
switch(choice)
{
case '1':
i=1;
get_next(T);
while(i<=T[0])
{
cout<<i<<"   "<<next[i]<<endl;
i++;
}
break;
case '2':
cout<<"请输入在主串中开始匹配的位置:"<<endl;
int pos;
cin>>pos;
             pos=Index_KMP(S,T,pos);
             if(pos)
{
cout<<"T is the substring of S and the postion is: "<<pos<<endl;
}
else
{
cout<<"T is not the substring of S"<<endl;
}
break;
         default:
break;


}
        }
return 0;
}

上面这个程序是一个KMP算法的例子,首先输入两个串,S和T,其中S作为主串,T作为模式串,然后我们计算T的匹配值也即是next,其中这一步是必须进行的,因为next决定着向右滑动的距离。用户可以按照选择,首先选择1然后选择2,最后返回值是当T是S的子串的时候返回的是T在S中的位置,否则返回为0,也即是匹配失败。



1 0
原创粉丝点击