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

本文介绍了一种优化的KMP字符串匹配算法,并提供了完整的C++实现代码。通过使用nextval数组来提高匹配效率,该算法能够快速定位模式串在主串中的出现位置。
#include<iostream>
#include<time.h>
#include<Windows.h>
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];
	}
}

在这里插入图片描述
上图是对应代码的运行结果

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值