64,646
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using std::cin; using std::cout; using std::endl;
using std::string;
int* get_next( const string& s );
int kmp_matcher( const string& txt , const string& pat );
int main( void )
{
string txt = "ababcabcacbab";
string pat = "abcac";
int loc = kmp_matcher( txt , pat );
cout << loc << endl;
return 0;
}
int* get_next( const string& s )
{
int N = s.size();
int* next = new int[N];
if( NULL == next )
return NULL;
int i = 0;
int j = -1;
next[ 0 ] = -1;
while( i < N )
{
if( -1 == j || s[ i ] == s[ j ] )
{
++i;
++j;
next[ i ] = j;
}
else
j = next[ j ];
}
return next;
}
int kmp_matcher( const string& txt , const string& pat )
{
int N = txt.size();
int M = pat.size();
if( 0 == N || 0 == M )
return -1;
int* next = get_next( pat );
int i = 0 , j = 0;
while( i < N && j < M )
{
if( txt[ i ] == pat[ j ] )
{ ++i;++j;}
else
j = next[ j ];
}
delete [] next;
if( M == j )
return i - M;
else
return -1;
}