/*
KMP算法:假设a[]是主串,b[]是模式串
*/
#include<iostream>
using namespace std ;
int next[1002] ;
void get_next(char a[])
{
int i = 0 , j = -1 ,lena = strlen(a);
next[0] = -1;
while( i < lena)
{
if( j == -1 || a[i] == a[j])
{
i ++ ;
j ++;
next[i] = j ;
}
else
j = next[j] ;
}
return ;
}
bool KMP(char a[],char b[])
{
int i = 0 , j = 0;
int lena = strlen(a),lenb = strlen(b) ;
while(i < lena)
{
if( j == -1 || a[i] == b[j])
{
i ++;
j ++ ;
}
else
j = next[j] ;
if(j>=lenb)
return true ;
}
return false;
}
int main(void)
{
char a[102] , b[102] ;
while(cin >> a>> b)
{
get_next(b);
if(KMP(a,b))
cout<<"匹配成功"<<endl;
else
cout<<"匹配失败"<<endl;
}
return 0 ;
}
KMP算法
最新推荐文章于 2024-11-16 09:45:51 发布