1. 程式人生 > >KMP演算法C++ 實現

KMP演算法C++ 實現

#include <iostream>
using namespace std;
void kmp_table(const char * P, int * next)
{
	next[0] = -1;
	unsigned int i = 0;
	int j = -1;

	while(i < strlen(P))
	{
		if( j==-1 ||P[i] == P[j])
		{
			++i;
			++j;
			next[i] = j ;			
		}
		else 
		{
			j = next[j];
		}
	}
}

int kmp_search(const char * T, const char * P)
{
	int n = strlen(T);
	int m = strlen(P);
    int * next = new int[m];

	kmp_table(P,next);

	for( int k = 0; k < m; k++)
	{
		cout<<next[k]<< " " ;
	}
	cout<<endl;
	int i=0,j=0;
	while(i<n && j<m)
	{
		if( j==-1|| T[i] == P[j])
		{
			i++;
			j++;
		}
		else
		{
			j = next[j];
		}
	}
	if(j==m)
		return i-m;
	else return 0;
}

int main()
{
	char * S = "acabaabaabcacaabc";
	char * W = "abaabcac";

	int p = kmp_search(S,W);

	cout<<"p = "<< p <<endl;
}