KMP算法

#include<iostream>
using namespace std;
typedef struct str
{
	char ch[20];
	int length;
}Str;
void getNext(Str sub, int next[])
{
	next[0] = -1;
	for (int i = 1; i < sub.length; i++)
	{
		//例:ABABABB  假设比较最后一个B,首先是比较ABABA 与 BABAB 也就是 ch[i]与ch[i+1]比较,如果一直是相等的,则j+t会等于i,
		//循环结束.如果中间不匹配了,则j依然移动到开始处,t++后为2,也就是比较ABAB 与 ABAB (1,3)(2,4)(3,5)(4,6)比较。
		//t一直加1,由此做到前缀与后缀的最大匹配
		int num = 0; //num代表当前next[i]数组里的值
		int t = 1;//t代表跨度
		int j = 0;// j作为数组下标的索引
		while(j+t<i)
		{
			if (sub.ch[j] == sub.ch[j + t])//匹配成功的话num,j就加一
			{
				num++;
				j++;
			}
			else//只要循环没有结束,却遇到了一个不匹配的情况都要重新开始
			{
				t++; //如果当前的跨度不匹配就要让跨度大一点,也就是前缀与后缀缩减一点
				j = 0;
				num = 0;
			}
		}
		//cout << num << endl;
		next[i] = num;
	}
}
int KMP(Str s, Str sub, int next[])
{
	int i = 0, j = 0;
	while (j < sub.length&&i<s.length)
	{
		if (s.ch[i] == sub.ch[j])
		{
			i++;
			j++;
		}
		else
		{
			j =  next[j];
			if (j == -1)//由于next数组第一个元素为-1,所以如果等于-1的话就让它从0开始判断
			{
				j = 0; 
				++i;
			}
		}
	}
	if (j == sub.length) //最后如果是因为sub长度匹配成功而跳出循环的,则 i-sub.length 为索引位置
		return i - sub.length;
	
	return -1;
}
int main(void)
{	
	Str s = { "ABABAAABABABB", 13 };
	Str sub={ "ABABB", 5 };
	int next[4]; // 下标为 sub的字符串长度
	memset(next, 0, sizeof(int) * 4);

	getNext(sub, next);
	int res=KMP(s, sub, next);
	if (res != -1)
		cout << res << endl;

	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值