查找子串-克努特-莫里斯-普拉特(KMP算法)

输入格式
两个字符串,各占一行,其中第一行为主串
输出格式
输出子串所在位置,若未能找到,则输出-1.
输入样例
输入样例:
aababcabcdabcde
abcd
输出样例
6

#include<iostream>
using namespace std;
#define N 100
int Index_KMP(char Str1[],char Str2[],int next[],int len1,int len2);
void get_next(char Str2[],int next[],int len2);
int main()
{
	int pos;
	int nex[N];
	char str1[N],str2[N];
	char next[N];
	cin>>str1>>str1;
	len1=strlen(str1);
	len2=strlen(str2);
	for(int i=len1-1;i>=0;j--)
		str1[i+1]=str1[i];
	for(int j=len2-1;j>=0;j--)
		str2[j+1]=str2[j];
	get_next(str2,nex,len2);
	pos=Index_KMP(str1,str2,nex,len1,len2);
	cout<<pos;
}
int Index_KMP(char* Str1,char* Str2,int next[],int len1,int len2)
{
	int i=1,j=1;	
	while(i<len1&&j<=len2)
	{
		if(j==0||S[i]==T[j]){++i;++j;}//继续比较后继字符串
		else j=next[j];//模式串向右移动
	}
	if(j>len2)	return i-len2;//匹配成功
	else return -1;//匹配失败
}//Index_KMP
void get_next(char Str2,int next,int len)
{//求模式串T的next函数值并存入数组next中
	i=1;
	next[1]=0;
	j=0;
	while(i<len)
	{
		if(j==0||Str2[i]==Str2[j])
		{
			++i;
			++j;
			if(T[i]!=T[j])	
				next[i]=j;
			else	
				next[i]=next[j];
		}
		else 
			j=next[j];
	}
}//get_next

猜你喜欢

转载自blog.csdn.net/weixin_43843978/article/details/88077799