KMP Pattern-Matching

parent 4dbfe528
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAXN 1000010
using namespace std;
int P[ MAXN + 1 ];
void prefix( char pattern[] )
{
int N = strlen( pattern );
P[ 0 ] = -1;
for( int i = 1; i < N; i++ ) {
int j = P[ i - 1 ];
while( true ) {
if( pattern[ i ] == pattern[ j + 1 ] ) {
P[ i ] = j + 1;
break;
}
else if( j == -1 ) {
P[ i ] = -1;
break;
} else {
j = P[ j ];
}
}
}
}
int KMP( char text[], char pattern[] )
{
int i = 0, j = 0, N = strlen( text ), M = strlen( pattern );
prefix( pattern );
while( true ) {
if( i == N ) {
break;
}
if( text[ i ] == pattern[ j ] ) {
if( j == M - 1 ) {
return i - M;
}
i++;
j++;
}
else if( j == 0 ) {
i++;
} else {
j = P[ j ];
}
}
return 0;
}
int main( void )
{
char text[ MAXN + 1 ], pattern[ MAXN + 1 ];
scanf("%s%s", text, pattern );
int res = KMP( text, pattern );
if( res ) {
printf("%s occurs in %s with shift %d\n", pattern, text, res + 1 );
} else {
printf("%s does not occur in %s\n", pattern, text );
}
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment