KMP 算法

19 篇文章 0 订阅


之前在看KMP算法~ 一头雾水 在百度查了半天资料~不是文字太多就是讲解复杂~ 


最终对于KMP算法的理解是看到阮一峰的 一篇文章才得以理解~

文章链接~字符串匹配的KMP算法

里边图文并茂的讲解了KMP算法的原理~但是里边并没有给出具体的算法~  网上的算法文章也写得很难懂~ 各种公式~ 最后终于在大维基百科的帮助下理解了KMP的算法~ 

它里边的伪代码写得很清楚~(维基百科 KMP)配合着看应该很容易理解~


代码:

#include <iostream>
using namespace std;

void MakeNext(char *a, int* &next)
{
	int len = strlen(a);
	next = new int[len];
	next[0] = -1;
	next[1] = 0;
	int count = 0;
	for (int pos = 2; pos < len; )
	{
		if (a[pos-1] == a[count])
		{
			count++;
			next[pos] = count;
			pos++;
		}
		else if ( count > 0 )
		{
			count = next[count];
		}
		else
		{
			next[pos] = 0;
			pos++;
		}
	}
}

int KmpSearch(char* a,char *s,int *next)
{
	int len = strlen(a);
	int lenS = strlen(s);
	int m = 0;
	int i = 0;
	while ( (m+i) < len && i < lenS )
	{
		if (a[m+i] == s[i])
		{
			i++;
		}
		else if(next[i] < 0)
		{
			m++;
			i = 0;
		}
		else
		{
			m = m + i - next[i];
			i = next[i];
		}
	}

	if ( i >= lenS )
		return m;

	return -1;
}

int main(int argc, char** argv) {
 
 	char a[] = "PARTICIPATE IN PARACHUTE";
	char s[] = "ACHUT";

	int *next;
	MakeNext(s,next);
	int k = KmpSearch(a,s,next);
	delete []next;
 
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值