KMP算法(C++實現)

// KMP算法
#include <iostream>
#include <string>
#include <vector>
using namespace std;

void get_next(string T,vector<int> &next){
	next.resize(T.size());
	int i=1,j=0;
	next[0] =1;
	while (i<T.length()-1){
		if(j==0 || T[i]==T[j])	{ ++i; ++j; next[i]=j; }
		else	j=next[j];//這裏又是一個遞歸,使用的是已經求出來的next[]數組。
	}
}
int Index(string S,string T,vector<int> &next){
	int i=0,j=0;
	while(i<S.length() && j<T.length()){
		if(j==0 || S[i]==T[j])	{ i++; j++;}
		else j=next[j];
	}
	if (j==T.length())	{return i-T.length();}
	else	return 0;
}
int main()
{
	string s="abcd";
	string a="cd";
	vector<int> next;
	get_next(a,next);
	int res=Index(s,a,next);
	cout << res <<endl;
	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章