kmp入門--kmp c++實現


#include<iostream>
#include<string>
#include<string.h>
using namespace std;
const int N=1100;
char s1[N+N],s2[N];
int next[N];
/*
void get_next(string t,int *next)
{
	int k=-1,j=0;
	next[0]=-1;
	while(t[j]!='\0')      //   ababaaaba
	{
		if(-1 == k||t[k]==t[j])  //只是在匹配串中出現
		{
			k++;     //k前綴
			j++;	 //j後綴
			next[j]=k;  //j前綴  next【j】意思是當前字符的前面有幾個相同的匹配字符串
		}   //並將其長度存入其字符的next數組中 以便使用(使用的時候是在 這個字符與另一個字符不相等的時候
		else  //可以將模式串中的j指針移到前面相同字符的後面 以減少前面需要匹配的次數) 重要
    		k=next[k]; // 前綴的回退  假如兩個字符不匹配則 將k從新從前綴開始 j則不用回退繼續與前綴匹配(減少了比較次數)
	}  //爲什麼這裏的 k不回退到最開始呢  原因在於 如果模式串長的話 前綴指針k的回退~~(基於 當前k字符的前面也有 匹配成功的字符串)
}  //結果只用回退到 上一個相同的前綴前面  再來比較字符串
*/

void get_next(char *t,int *next)
{
	int p=strlen(t);
	next[0]=-1;
	int k=-1,j=0;
	while(j<p)
	{
		if(-1==k||t[k]==t[j])
		{
			k++;
			j++;
			if(t[j]!=t[k])
				next[j]=k;
			else
				next[j]=next[k];
		}
		else
		    k=next[k];
	}
}
int kmp(char* s,char* t)
{
	int i,j;
	int len=strlen(t),lens=strlen(s);
	
	get_next(t,next);
	i=j=0;
	while(i<lens&&j<len)
	{
		if(j==-1||s[i]==t[j])
		{
			i++;
			j++;
		}
		else
			j=next[j];
	}
	if(j>=len)
		return 1;
	return 0;
}
int main()
{
	int i,j,l;
	while(cin>>s1>>s2)
	{
		l=strlen(s2);

		if(kmp(s1,s2))
			cout<<"yes"<<endl;
		else
			cout<<"no"<<endl;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章