#include<iostream>
using namespace std;
void get_next( char str2[] , int next[] , int length2 ) {
int i , j;
i = 0;
j = -1;
next[ 0 ] = -1;
while( i < length2 ) {
if( ( j == -1 ) || ( str2[ i ] == str2[ j ] ) ) {
i ++;
j ++;
next[ i ] =j;
}
else {
j = next[ j ];
}
}
}
void kmp( char str1[] , char str2[ ] , int length1 , int length2 ) {
int i , j;
int *next;
next = ( int * ) malloc( sizeof( int ) * length2 );
get_next( str2 , next , length2 );
i = j = 0;
while( ( i < length1 ) && ( j < length2 ) ) {
if( ( j == -1 ) || ( str1[ i ] == str2[ j ] ) ) {
i ++;
j ++;
}
else {
j = next[ j ];
}
if( j >= length2 ) {
printf( "%d OK\n" , i - j );
j = 0;
//感觉这里i是需要回的,比如子串和主串全都是字符a
i = i - j + 1;
}
}
}
int main( ) {
char str1[ 1000 ];//主串
char str2[ 10 ]; //子串
printf( "请输入主串:\n" );
scanf( "%s" , str1 );
printf( "请输入子串:\n" );
scanf( "%s" , str2 );
kmp( str1 , str2 , strlen( str1 ) , strlen( str2 ) );
return 0;
}
//测试用例
//ababcabcacbab
//abcac
KMP
最新推荐文章于 2023-01-23 18:57:44 发布