KMP算法简单复习及实现 C++

博客主要围绕KMP算法展开,对其进行简单复习,并给出了该算法在C++语言中的实现,帮助读者回顾KMP算法相关知识及了解其在C++里的具体实现方式。
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int *buildNext(char *p);
int match(char *P, char *T);


int main(int argc, char *argv[])
{

	const char *T = "thisiathekmpteststring";
	const char *P = "test";

	int n = match((char *)P, (char *)T);

	printf("T : %s\n", T);
	printf("P : %s\n", P);
	printf("n : %d\n", n);

	system("pause");
	return 0;
}

int *buildNext(char *p)
{
	int m = strlen(p), j = 0;
	int *next = new int[m];

	int t = next[0] = -1;//约定

	while (j < m - 1)
	{
		if (t < 0 || p[j] == p[t]) {
			j++; t++;
			next[j] = t;
		}
		else {
			t = next[t];
		}
	}
	return next;
}

int match(char *P, char *T)
{
	int *next = buildNext(P);

	int p_n = strlen(P), i = 0;
	int t_n = strlen(T), j = 0;

	while (i < p_n && j < t_n)
	{
		if (i < 0 || T[j] == P[i]) {
			j++; i++;
		}
		else {
			i = next[i];
		}
	}
	delete[] next;
	return j - i;
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值