KMP函数实现

大神代码:https://blog.csdn.net/v_july_v/article/details/7041827

 

本篇是接着上一篇的理论写了一个简单的Demo,上面的链接是代码的原地址,下面是我写的Demo,供大家参考。

2. 匹配函数

int KMPSearch(char* a,char* p,int * next){
	int a_len = strlen(a);
	int p_len = strlen(p);
	int i=0, j=0;

	while (i < a_len&&j < p_len){
		if (j >= 0){
			cout << "after : a[i] is : " << a[i] << ", p[j] is : " << p[j] << ", i is : " << i << ", j is : " << j << endl;
		}else{
			cout << "after : a[i] is : " << a[i] << ", p[j] is : ** " <<  ", i is : " << i << ", j is : " << j << endl;
		}
		
		if (j == -1 || a[i] == p[j]){
			++i;
			++j;
		}
		else
		{
			j = next[j];
		}		
	}
	if (j == p_len){
		return i - j;
	}
	else{
		return -1;
	}
}

下面是程序汇总

 

#include "stdafx.h"
#include "iostream"
using namespace std;

void Next(char * a,int * next){
	int n = strlen(a);
	next[0] = -1;
	int k = -1;
	int j = 0;
	while (j<n-1){
		//cout << "befor :a is : " << a << ", next[k] is : " << next[k] << ", j is : " << j << ", K is : " << k << endl;
		if (k == -1 || a[j] == a[k]){
			++k;
			++j;
			//next[j] = k;
			if (a[j] != a[k])
				next[j] = k;
			else{
				next[j] = next[k];
			}
		}
		else
		{
			k = next[k];
		}
		//cout << "after :a is : " << a << ", next[k] is : " << next[k] << ", j is : " << j << ", K is : " << k << endl;
	}
}

int KMPSearch(char* a,char* p,int * next){
	int a_len = strlen(a);
	int p_len = strlen(p);
	int i=0, j=0;

	while (i < a_len&&j < p_len){
		if (j >= 0){
			cout << "after : a[i] is : " << a[i] << ", p[j] is : " << p[j] << ", i is : " << i << ", j is : " << j << endl;
		}else{
			cout << "after : a[i] is : " << a[i] << ", p[j] is : ** " <<  ", i is : " << i << ", j is : " << j << endl;
		}
		
		if (j == -1 || a[i] == p[j]){
			++i;
			++j;
		}
		else
		{
			j = next[j];
		}

		
	}
	if (j == p_len){
		return i - j;
	}
	else{
		return -1;
	}

}

int _tmain(int argc, _TCHAR* argv[])
{
	char a[] = "abab";
	char p[] = "abacabayabab";
	int n = strlen(a);
	int next[4] = { -2};
	Next(a,next);
	int Pos = KMPSearch(p, a, next);

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值