KMP文字列マッチングアルゴリズム実装

1334 ワード

kmp文字列マッチングアルゴリズムC++コード実装
#ifndef __H_KMP_H__
#define __H_KMP_H__
#include 

//  next  
int _fill_next_array(char* comp, int len, int* next)
{
	int i = 0;
	int j = -1;
	next[0] = -1;
	while(i < len - 1)
	{
		if(j == -1 || comp[i] == comp[j])
		{
			++i;
			++j;
			if(comp[i] != comp[j])
			{
				next[i] = next[j];
			}else{
				next[i] = j;
			}
		}else{
			j = next[j];
		}
	}
	return 0;
}

//    ,                 
bool is_contain_substring(char* src, char* comp)
{
	if((NULL == src && NULL != comp) || (NULL != src && NULL == comp))
		return false;
	int len1 = strlen(src);
	int len2 = strlen(comp);
	if(len1 < len2)
		return false;

	int* next = new int[len2];
	_fill_next_array(comp, len2, next);
	int j = 0;
	for(int i=0; i


#include "KMP.h"

int main()
{
	std::cout << is_contain_substring("abcdabcabcdeabccba", "abcde") << std::endl;
	return 0;
}