数据结构——字符串匹配算法(BF&KMP)

#include
#include
#include
using namespace std;
#define SIZE 100
#pragma warning(disable:4996)
int BFmatch(char a[], char b[]);//BF算法字符串匹配
int KMPmatch(char a[], char b[],int next[]);//KMP算法字符串匹配
void getnext(char a[], int b[]);//生成next数组
void getnextval(char a[], int b[], int c[]);//对生成的next数组进行改进并生成nextval
int main()
{
	int next[SIZE]; next[0] = SIZE;
	int nextval[SIZE];
	int pos=1;
	char S[SIZE];//存储主串
	char T[SIZE];//存储模式串
	char P[SIZE];//公共存储字符串
	cout << "请输入您的主串" << endl;
	cin >> P; 
	S[0] = char(strlen(P));
	strcpy(S + 1, P);
	memset(P, 0, sizeof(P));
	cout << "请输入您需要匹配的模式串" << endl;
	cin >> P;
	T[0] = char(strlen(P));
	strcpy(T + 1, P);
	//BF算法进行字符串匹配
	/*if (int(S[0]) < int(T[0]))cout << "不符合匹配规则,失败" << endl;
	else pos = BFmatch(S, T);
	if (pos == 0)cout << "匹配失败";
	else cout << "匹配成功,成功位置在主串的第" << pos << "位上至第" << pos + int(T[0]) - 1 << "位上";*/
	//KMP算法进行字符串匹配
	/*getnext(T, next);
	if (int(S[0]) < int(T[0]))cout << "不符合匹配规则,失败" << endl;
	else pos = KMPmatch(S, T, next);
	if (pos == 0)cout << "匹配失败";
	else cout << "匹配成功,成功位置在主串的第" << pos << "位上至第" << pos + int(T[0]) - 1 << "位上";*/
	//KMP算法并优化next数组进行字符串匹配
	getnext(T, next);
	getnextval(T, next, nextval);
	if (int(S[0]) < int(T[0]))cout << "不符合匹配规则,失败" << endl;
	else pos = KMPmatch(S, T,nextval);//pos = BFmatch(S, T);
	if (pos == 0)cout << "匹配失败";
	else cout << "匹配成功,成功位置在主串的第" << pos << "位上至第"<<pos+int(T[0])-1<<"位上";
	return 0;
}
int BFmatch(char a[], char b[])//BF算法字符串匹配
{
	int i = 1; int j = 1;
	while (i <= int(a[0]) && j <= int(b[0]))
	{
		if (a[i] == b[j]) 
		{
			i++; j++;
		}
		else 
		{
			i = i - j + 2;
			j = 1;
		}
	}
	if (j > int(b[0]))return i - j + 1;
	else return 0;
}
int KMPmatch(char a[], char b[],int next[])//KMP算法字符串匹配
{
	int i = 1; int j = 1;
	while (i <= int(a[0]) && j <= int(b[0]))
	{
		if (j==0||a[i] == b[j])
		{
			i++; j++;
		}
		else j = next[j];
	}
	if (j > int(b[0]))return i - int(b[0]);
	else return 0;
}
void getnext(char a[],int b[])//生成next数组
{
	int i = 1; b[1] = 0; int j = 0;
	while (i<int(a[0]))
	{
		if (j == 0 || a[i] == a[j])
		{
			i++;
			j++;
			b[i] = j;
	    }
		else j = b[j];
	}
}
void getnextval(char a[], int b[],int c[])//对生成的next数组进行改进
{
	c[0] = SIZE;
	c[1] = 0;
	for(int i=2;i <= int(a[0]);i++)
	{
		if (a[i] == a[b[i]])
		{
			c[i] = b[b[i]];
			b[i] = b[b[i]];
		}
		else c[i] = b[i];
	}
}

数据结构——字符串匹配算法(BF&KMP)_第1张图片
上图是对应代码的运行结果

你可能感兴趣的:(算法,数据结构,字符串)