kmp算法和bf算法实现

#include<iostream>
#include<Stdio.h>
#include<Conio.h>
#include<Stdlib.h>
using namespace std;
#define MAXSIZE 255//定义字符串做最大长度
typedef unsigned char SString[MAXSIZE+1];//数组第一个保存长度
int Index(SString s,SString t,int pos);//声明BF算法
void get_nextval(SString T,int nextval[]);//声明get_nextval
int Index_KMP(SString S,SString T,int pos);//声明KMP算法
void main()
{
	int i=0,a=0;
	SString s,t;
	char ch=0;
	cout<<"请输入字符串s:\n";
	while(ch!=10){
		ch=s[++i]=getchar();
	}
	s[0]=i-2;//S的长度,除去最后的回车换行符
	i=0;
	ch=0;
	cout<<"请输入模式串:\n";
	while(ch!=10)
	{
		ch=t[++i]=getchar();
	}
	t[0] = i-2;//T的长度,除去最后的回车换行符
	//a=Index(s,t,0);//调用BF算法
	a = Index_KMP(s,t,0);
    if(a)
		 cout<<"第"<<a<<"个字符开始匹配\n";
     else
        printf("S中POS之后不存在T这样的字串\n");
}
int Index(SString s,SString t,int pos)//BF算法
{
    int i=pos,j=1;
    while(i<=s[0]&&j<=t[0])
    {
        if(s[i]==t[j])
        {
            i++;j++;
        }
        else
        {
            i=i-j+2;//主串指针回溯到刚刚比较的下个位子
            j=1;//模式串指针回溯至第一位
        }
    }
    if(j>t[0])
        return i-t[0];
    else
        return 0;
}
void get_nextval(SString T,int nextval[])
{
	//求模式串T的next函数修正值并存入数组nextval
	int i = 1,j = 0;
	nextval[1] = 0;
	while(i < T[0])
	{
		if(j==0 || T[i] == T[j])
		{
			++i;
			++j;
			if(T[i] != T[j])
				nextval[i] = j;
			else
				nextval[i] = nextval[j];
		}
		else
			j = nextval[j];
	}
}
int Index_KMP(SString S,SString T,int pos)
{
	//利用模式串T的next函数求T在主串S中第pos个字符之后的位置
	//利用KMP算法,其中T非空,1<=pos<=StrenLength(S)
	int i = pos,j = 1;
	int next[512];//定义一个数组
	get_nextval(T,next);//获得next数组
	while(i <=S[0] && j<=T[0])
	{
		if(j == 0 || S[i] == T[j])
		{
			++i;
			++j;
		}
		else
			j = next[j];
	}
	if(j > T[0])
		return i - T[0];
	else
		return 0;
}

 

你可能感兴趣的:(KMP)