数据结构--KMP

KMP

KMP算法是用于匹配子串的算法,即给一个字符串string,一个模板串patterm,匹配子串就是从string中找到第一个子串同patterm相同。

这个算法太抽象了,能力有限讲不清楚,建议看mooc的视频学习!!!!!!!!

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std ;

void buildmatch(int match[] , char patterm [])
{
	int len = strlen (patterm);
	match[0] = -1 ;
	int i,j;
	for (j = 1 ; j <len ; j++ )
	{
		i = match[j-1] ;
		while (i>=0 && patterm[i+1]!= patterm[j]) i = match[i];
		
		if (patterm[i+1] == patterm[j])
			match  [j] = i+1 ;
		else match[j] = -1 ;
	}
}

int KMP (char str[] , char patterm[])
{
	int lenstr  = strlen(str);
	int lenpatterm = strlen(patterm);
	int match[lenpatterm];
	
	if (lenpatterm >  lenstr  )
		return -1;
	
	buildmatch(match , patterm);
	
	int i = 0, j = 0 ;
	while (i<lenstr  && j <lenpatterm )
	{
		if (str[i] == patterm[j])
		{
			i++ ;j++;		
		}
		else if (j>0) j = match[j-1] +1;
		else i++ ;
	}
	return (j==lenpatterm)? i-lenpatterm : -1 ; 
}

int main ()
{
	char string[10000];
	char patterm[10000];
	cin >> string >> patterm;
	int pos = KMP(string ,patterm);
	if (pos <0)
	cout <<"no found";
	else 
	cout <<string+pos;
	
	return 0;
	
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值