关于KMP算法

复习的时候随便写写的,用git太麻烦,就用csdn保存下。KMP算法写起来很短,但是精髓是它的思想不太好理解,主串不用回溯,是因为模式串自己与自己比较匹配可以得出相应的next值,然后模式串向右滑动,例如,模式串abcdxxxxxabcixxxx在第i位失配,只需要模式串滑到d与主串继续比较。。。哎呀表达得不太好,书上这部分内容讲了三大页,毕竟是世界十大伟大算法之一。

#include<iostream>
#include<string>
using namespace std;
int NEXT[100] = { 0 };
void getNext(string &s, int next[]) {
	int i = 1,j = 0;
	next[1] = 0;
	while (i < s.length()) {
		if (j == 0 || s[i-1] == s[j-1]) {
			i++; j++;
			next[i] = j;
		}
		else
			j = next[j];
	}
}


int KMP(string S, string T, int pos) {
	int i = pos, j = 1;
	while (i <=S.length() &&j <= T.length()) {
		if ( j == 0 || S[i-1] == T[j-1]) {
			i++; j++;
		}
		else {
			j = NEXT[j];
		}
	}
	if (j > T.length()-1)
		return i-T.length();
	else
		return-1;
}
void main() {
	int choice=0;
	do {		
		
		cout << "请输入主串" << endl;
		string a, b;
		getline(cin, a);
		cout << "请输入模式串" << endl;
		getline(cin, b);
		getNext(b, NEXT);
		//cout << "测试数据:" <<  endl;
		//for (int i = 0; i < b.length(); i++)
		//	cout << NEXT[i + 1];
		cout << KMP(a, b, 1)<<endl;
		cout << "输入1继续,2退出"<<endl;
		cin >> choice;
		char sbuf[1024];
		// ...
		// fflush(stdin); // 用下面一句代替

		fgets(sbuf, 1024, stdin);
	} while (choice != 2);
}

好吧,我觉得第一版写得很水,下面第二版应该好很多

/***字符串匹配算法***/
#include<cstring>
#include<iostream>
using namespace std;

#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
#define MAXSTRLEN 255   		//用户可在255以内定义最长串长
typedef char SString[MAXSTRLEN+1];		//0号单元存放串的长度

Status StrAssign(SString T, char *chars) { //生成一个其值等于chars的串T
	int i;
	if (strlen(chars) > MAXSTRLEN)
		return ERROR;
	else {
		T[0] = strlen(chars);
		for (i = 1; i <= T[0]; i++)
			T[i] = *(chars + i - 1);
		return OK;
	}
}
//计算next函数值
void get_next(SString T, int next[])
{ //求模式串T的next函数值并存入数组next
	int i = 1, j = 0;
	next[1] = 0;
	while (i < T[0])
		if (j == 0 || T[i] == T[j])
		{
			++i;
			++j;
			next[i] = j;
		}
		else
			j = next[j];
}//get_next

//KMP算法
int Index_KMP(SString S, SString T, int pos, int next[])
{ 	// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置的KMP算法
	//其中,T非空,1≤pos≤StrLength(S)
	int i = pos, j = 1;
	while (i <= S[0] && j <= T[0])
		if (j == 0 || S[i] == T[j]) // 继续比较后继字
		{
			++i;
			++j;
		}
		else
			j = next[j]; // 模式串向右移动
	if (j > T[0]) // 匹配成功
		return i - T[0];
	else
		return 0;
}//Index_KMP

int main()
{
	SString S;
	StrAssign(S,"aaabbaba") ;
	SString T;
	StrAssign(T,"abb") ;
	int *p = new int[T[0]+1]; // 生成T的next数组
	get_next(T,p);
	cout<<"主串和子串在第"<<Index_KMP(S,T,1,p)<<"个字符处首次匹配\n";
	return 0;
}

猜你喜欢

转载自blog.csdn.net/asd8888123456/article/details/86363434