前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >KMP模式匹配算法改进---nextval数组

KMP模式匹配算法改进---nextval数组

作者头像
大忽悠爱学习
发布2021-03-15 18:32:18
1.5K0
发布2021-03-15 18:32:18
举报
文章被收录于专栏:c++与qt学习

建议先复习一个KMP算法

KMP模式匹配算法的缺陷

这里可以发现,2345步骤,其实都是多余的判断,由于T串中的2345位置的字符都与首位的a相等,那么可以利用首位next1的值去取代与它相等1的字符后续的nextj的值,因此我们要对next函数进行改良-------我们把改良后的next数组叫做nextval

求nextval数组

代码语言:javascript
复制
#include<iostream>
using namespace std;
//nextval数组
void get_nextval(string T,int* nextval)
{
	int i = -1; //指向前缀
	int j = 0; //指向后缀
	nextval[0] = -1;
	while (j < (T.length())-1)
	{
		if (i == -1 || T[i] == T[j])
		{
			i++;
			j++;
            //如果前缀字符与后缀字符不同
			if (T[i] != T[j])
			{
				//当前nextval[j]的值等于i位置的值
				nextval[j] = i;
			}
			else 
			{
				//如果前缀字符与后缀字符相同,则将前缀字符的nextval值赋值给后缀字符的nextval值
				nextval[j] = nextval[i];
			}

		}
		else 
		{
			i= nextval[i];
		}
	}
}
void test()
{
	//测试nextval数组-----------------
	string T = "ababaaaba";
	int nextval[9] = {};
	get_nextval(T, nextval);
	for (int i = 0; i < 9; i++)
	{
		cout << nextval[i] << "  ";
	}
}
int main()
{
	test();
	system("pause");
	return 0;
}

KMP改进代码:

代码语言:javascript
复制
#include<iostream>
using namespace std;
//nextval数组
void get_nextval(string T,int* nextval)
{
	int i = -1; //指向前缀
	int j = 0; //指向后缀
	nextval[0] = -1;
	while (j < (T.length())-1)
	{
		if (i == -1 || T[i] == T[j])
		{
			i++;
			j++;
            //如果前缀字符与后缀字符不同
			if (T[i] != T[j])
			{
				//当前nextval[j]的值等于i位置的值
				nextval[j] = i;
			}
			else 
			{
				//如果前缀字符与后缀字符相同,则将前缀字符的nextval值赋值给后缀字符的nextval值
				nextval[j] = nextval[i]+1;
			}

		}
		else 
		{
			i= nextval[i];
		}
	}
}
//改进KMP改进
int test(string S,string T,int* nextval)
{
	int i =0;//指向主串S
	int j = 0; //指向子串T
	while (i <= S.length() - 1 && j <= T.length() - 1)
	{
		if (j == 0 || S[i] == T[j])
		{
			i++;
			j++;
		}
		else 
		{
			j = nextval[j];
		}
	}
	cout << "i=" << i << endl;
	cout << "j=" << j << endl;
	if (j == T.length())
	{
		return i - j;
	}
	return -1;
}
void test()
{
	string S = "aaaabaaaaaxcdef";
	string T = "aaaaax";
	int nextval[6] = {};
	get_nextval(T, nextval);
	int ret=test(S, T, nextval);
	cout << "子串T在主串S中的起始位置为:"<<ret << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • KMP模式匹配算法的缺陷
  • 求nextval数组
  • KMP改进代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档