Quantcast
Channel: NC.Blog
Viewing all articles
Browse latest Browse all 13

KMP算法

$
0
0

自己撸的KMP

#include <iostream>
#include <string>
using namespace std;
bool GetNext(const char * pStr,int *pNext);
int Kmp(const char *pFStr,const char *pSStr);
int main()

{
	int *p = NULL;
	cout << Kmp("abcabcabcd","abcd");
	return 0;
}

int Kmp(const char *pFStr,const char *pSStr)
{
	int i = 0,j = 0;
	int *pNext = NULL;
	int iFStrLen = strlen(pFStr);
	int iSstrLen = strlen(pSStr);
	pNext = new int[iSstrLen];
	GetNext(pSStr,pNext);
	if(iSstrLen > iFStrLen)
	{
		return -1;
	}
	while(i < iFStrLen && j < iSstrLen)
	{
		if(j == -1 || pFStr[i] == pSStr[j])
		{
			++i;
			++j;
		}
		else
		{
			j = pNext[j];
		}

	}
	delete[] pNext;
	if(j >= iSstrLen)
	{
		return i - iSstrLen;
	}
	else
	{
		return -1;
	}
}
bool GetNext(const char * pStr,int *pNext)//获取next数组
{
	if(pStr == NULL || pNext == NULL)
	{
		return false;
	}
	int i = 0,j = -1;
	int iSize = strlen(pStr);
	pNext[i] = j;
	while(i < iSize - 1)
	{
		if(j == -1 || pStr[i] == pStr[j])//继承获取next数组的值
		{
			++i;
			++j;
			pNext[i] = j;
		}
		else
		{
			j = pNext[j];//回溯
		}
	}
	return true;
}



Viewing all articles
Browse latest Browse all 13

Trending Articles