KMP字符串匹配算法

KMP字符串匹配算法,重点在于Next值的计算,下面是这个算法的代码:

#include<iostream>
#include<string>
using namespace std;

#define size 8


int main()
{
	int ifr;
	int next[size]={0,0,0,0,0,0,0};
	char pst[size]={'a','b','a','a','b','c','a','c'};
	char sstr[17]={'a','c','a','b','a','a','b','a','a','b','c','a','c','a','a','b','c'};
	

	void getNext(int next[size]);
	int  fastPattStr(const char *sstr,const char *pst,int *next);
	
	cout<<"KMP字符串匹配算法"<<endl;
	getNext(next);
	for(int i=0;i<size;i++)
		cout<<next[i]<<" ";
		cout<<endl;
	if(ifr!=-1)
	{
		cout<<"Location:"<<fastPattStr(sstr,pst,next)<<endl;
	}
	else
	{
		cout<<"字符串不能正确匹配"<<endl;
	}
	return 0;
}

/*寻找下一次开始比较位置:递推,根据已知求未知*/
void getNext(int next[size])
{
	int j=0;
	/*j=0时,next[0]=-1*/
	next[0]=-1;
	int k=-1;
	//int max=0;
	//int r=0;
	/*直到求到模式串的结尾*/
	while(j<size)
	{
		if(k==-1 || pst[k]==pst[j])
		{
			j++;
			k++;
			next[j]=k;
		}
		else
		{
			k=next[k];
		}
		/*if(k>j-1)
		{
			/*其他情况
			next[j]=0;
		}
		else
		{
			/*k>=0且k<j-1 next[j]=k+1
			do
			{	
				r=j-k-1;
				for(int i=0;i<=k;i++)
				{
					if(pst[i]==pst[r])
						r++;
					else
						break;
				}
				if(max<k+1)max=k+1;				
				k++;
			}while(k<j-1);
			next[j]=max;
		}*/
		
	}
	
}
/*字符串匹配函数*/
int  fastPattStr(const char *str,const char *pstr ,int next[])
{
	int s_pos=0;
	int p_pos=0;
	int s_len;
	s_len=17;
	
	/*如果模式串位置小于目标串索引*/
	while(s_pos<s_len && p_pos<size)
	{
		if(p_pos==-1||str[s_pos]==pstr[p_pos])
		{
			s_pos++;
			p_pos++;		
		}
		else
		{
			//下面这一句出错了,和目标串的索引没有关系
			//p_pos=next[s_pos];
			p_pos=next[p_pos];
		}
	}
	
	if(p_pos<size-1)
		return -1;
	else
		return s_pos-size;
}

  

posted @ 2013-09-25 15:07  李VS超  阅读(289)  评论(0编辑  收藏  举报