KMP算法

这个算法看了。很久啊。很难懂。。虽说现在会了。。不过。应用的根本不熟练

老规矩。。。贴下代码。。纪念下。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
	char *ch;
	int length;
}SString;

int strKMP(SString *S,SString *T,int pos,int next[]);	//求在主窜中S中第pos个字符之后的位置的KMP算法
void get_next(SString *T,int next[]);	//求模式串中T的next函数值并存入数组next
int StrAssign(SString *str,char *chars);	///生成一个与chars相等的字符串


int main()
{
	SString S={NULL,0},T={NULL,0};
	int pos;
	int next[50];
	StrAssign(&S,"ababcabcacbab");
	StrAssign(&T,"cacba");
	get_next(&T,next);

	pos=strKMP(&S,&T,0,next);
	printf("%d\n",pos);
	return 0;
}
int StrAssign(SString *str,char *chars)
{
	if(str->ch)		//清空str
		free(str->ch);
	str->ch = (char *)malloc((strlen(chars)+1)*sizeof(char));
	if( !str->ch )
		return 0;
	str->length = strlen(chars);
	strcpy(str->ch,chars);	//复制字符串

	return str->length;
}

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

void get_next(SString *T,int next[])
{
	int i=0,j=-1;
	next[0]=-1;
	while(i < T->length-1)	//这里注意下
	{
		if(j==-1 || T->ch[i] == T->ch[j])
		{
			i++; j++;
			if(T->ch[i] != T->ch[j])
				next[i]=j;
			else
				next[i] = next[j];
		}
		else
			j = next[j];
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值