#include <string>
using namespace std;
//来自网络
//以计算下一个元素的next值为中心
static void preKmp(const char *x, int len, int kmpNext[])
{
int i, j;
i = 0;
j = kmpNext[0] = -1;
while (i < len)
{
while (j > -1 && x[i] != x[j])
j = kmpNext[j];
i++;
j++;
if (x[i] == x[j])
kmpNext[i] = kmpNext[j];
else
kmpNext[i] = j;
}
}
//原创
//以计算当前next值为中心
//在while循环中修正next会错过修正之间的序列
static void MyPreKmp( const char* x, int len, int kmpNext[] )
{
kmpNext[0] = -1;
int index = 1;
while ( index < len )
{
//计算index处的next值
int i = index-1;
while ( true )
{
int j = kmpNext[ i ];
if ( -1 == j || x[ j ] == x[ index-1 ] )
{
kmpNext[ index ] = j+1;
break;
}
i = j;
}
index++;
}
for ( int i=1; i<len; i++ )
{
if ( x[i] == x[ kmpNext[i] ] )
kmpNext[i] = kmpNext[ kmpNext[i] ];
}
}
void main()
{
string s ="abaabcac";
int buffer[ 100 ];
MyPreKmp( s.c_str(), s.size(), buffer );
preKmp( s.c_str(), s.size(), buffer );
}
KMP算法非递归实现——菜鸟与高手的区别
最新推荐文章于 2019-07-03 15:49:10 发布