KMP算法实现

(1)KMP算法

          KMP算法是一种字符串匹配算法。学习这种字符串匹配算法最好是以例子的形式理解其思想。推荐一个用图片说明算法过程的博客,浅显易懂:

          http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

(2)算法实现

#include 

using namespace std;

int kmp(char* str, char* pattern)
{
	if(str == NULL || pattern == NULL)
		return -1;
	int p_len = strlen(pattern);
	int* next = new int[p_len];
	next[0] = -1;
	for(int i=1; i=0&&pattern[pre+1]!=pattern[i])
			pre = next[pre];
		if(pattern[pre+1] == pattern[i])
			next[i] = pre+1;
		else
			next[i] = -1;
	}
	for(int i=0; i


你可能感兴趣的:(算法设计,C++)