码迷,mamicode.com
首页 > 编程语言 > 详细

KMP算法

时间:2019-12-23 22:46:23      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:i++   pre   char   str   val   dex   sharp   eof   amp   

typedef struct {
	char str[MAX];
	int length;
}SString;

  BF算法

int Index(SString *S, SString *T)
{
	int i, j;
	i = 1; j = 1;
	while (i<=S->length&&j<=T->length)
	{
		if (S->str[i] == T->str[j])
		{
			i++;
			j++;
		}
		else
		{
			i = i - j + 2;
			j = 1;
		}
	}
	if (j > T->length)
		return i - T->length;
	else
		return 0;
}

  KMP算法

int Index_KMP(SString *S, SString *T,int *next)
{
	int i = 1, j = 1;
	while (i <= S->length && j <= T->length)
	{
		if (j == 0 || S->str[i] == T->str[j])
		{
			i++;
			j++;
		}
		else
			j = next[j];
	}
	if (j > T->length)
		return i - T->length;
	else
		return 0;
}

  求next数组

void get_next(SString* S, int *&next)
{
	next=(int *)malloc(sizeof(int)*S->length);
	int i = 1, j = 0;
	next[1] = 0;
	while (i <= S->length)
	{
		if (j == 0 || S->str[i] == S->str[j])
		{
			i++;
			j++;
			next[i] = j; 
		}
		else
			j = next[j];
	}
}

  求nextval数组

void get_nextval(SString*T,int *&nextval)
{
	nextval=(int *)malloc(sizeof(int)*T->length);
	int i = 1, j = 0;
	nextval[1]=0;
	while(i<=T->length)
	{
		if(j==0||T->str[i]==T->str[j])
		{
			i++;j++;
			if(T->str[i]!=T->str[j])
				nextval[i]=j;
			else
				nextval[i]=nextval[j];	
		}
		else
			j=nextval[j];
	}
}

  

KMP算法

标签:i++   pre   char   str   val   dex   sharp   eof   amp   

原文地址:https://www.cnblogs.com/KIROsola/p/12088491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!