`
tousin
  • 浏览: 8138 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
社区版块
存档分类
最新评论

KMP算法实现

阅读更多
#include "StdAfx.h"
#include "KMP.h"

KMP::KMP(void)
{
	str = "dasfqwerfadfaslkfjoijmqwemlkefadfaslk";
	substr = "fadfas";
	this->next = new int[strlen(this->substr)+1];
}

KMP::~KMP(void)
{
	delete this->next;
}

void KMP::run()
{
	cout << this->str << endl;
	cout << this->substr << endl;
	computePrefix();

	int k = 0,i=0;
	int tLen = strlen(this->str);
	int pLen = strlen(this->substr);

	for(;i<tLen;i++)
	{
		while(k > 0 && (this->substr[k] != this->str[i]))
			k = this->next[k];
		if(this->substr[k] == this->str[i])
			k++;
		if(k == pLen)
		{
			cout << "Pattern occurs with position : " << i - pLen + 1 << endl;
			k = this->next[pLen-1];
		}
	}
}

void KMP::computePrefix()
{
	int len = strlen(this->substr);

	int k = 0,i=1;

	this->next[0] = 0;

	for(;i < len;i++)
	{
		while( k > 0 && (substr[k] != substr[i]))
			k = this->next[k];
		if(substr[k] == substr[i])
			k++;

		this->next[i] = k;
		cout << k << " ";
	}

	cout << endl;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics