//
#include<bits/stdc++.h>
using namespace std;
const int N=1111;
int abfix[N];
void init( const string &p )
{
int i,j;
abfix[0]=abfix[1]=0; //
for( i=1;i<p.size();i++ )
{
j=abfix[i];
while( j && p[j]!=p[i] ) j=abfix[j]; // j 通过 abfix 前移
if( p[j]==p[i] ) abfix[i+1]=j+1;
else abfix[i+1]=0;
}
}
void KMP( const string &s,const string &p )
{
int i,j;
for( i=j=0;i<s.size();i++ )
{
while( j && s[i]!=p[j] ) j=abfix[j]; // 滑动 j // j==0失配 按各不相同情况处理
if( s[i]==p[j] ) j++; // 匹配推进
if( j==p.size() ) cout<<( i-p.size()+1 )<<endl; // 打印位置
}
}
int main()
{
string s,p;
while( cin>>s>>p )
{
init( p );
KMP( s,p );
}
return 0;
}
模板_字符串算法_KMP
猜你喜欢
转载自blog.csdn.net/qq_63173957/article/details/125286229
今日推荐
周排行