#include “stdafx.h”
#include<iostream>
#include<time.h>
#include<string>
using namespace std;
void init(string ,string);
void show(char [],int);
int kmp(string ,string,int pos);
void get_next(char*,int *);
string s1,t1;
int m,n;
char *s;
char *t;
int *next;
/*************************MAIN**************************************/
int main(int argc[],char*args[])
{
double t=clock();
cout<<“起始时间:”<<t<<endl;
cout<<“找到位置为:”<<kmp(“acbsabcaacabaabaabcacaabc”,”abaabca”,1)<<endl;
delete[] s;
delete[] next;
cout<<“结束时间:”<<clock()<<endl;
cout<<“耗时:”<<(clock()-t)/1000<<“毫秒!”<<endl;
return 0;
}
/**********************++++NEXT++++********************************/
void get_next(char s[],int ne[])
{
ne =new int[n+1];
next=new int[n+1];
ne[0]=9999;
int i(1),j(0);
ne[1]=0;
while(i<=(int)(t[0]))//数组是字符型的,要转化为整数
{
if(j==0||t[i]==t[j]){++i;++j;ne[i]=j;}
else j=ne[j];
}
for( i=1;i<=n;i++)
{
cout<<“next[“<<i<<“]=”<<ne[i]<<endl;
next[i]=ne[i];
}
}
/********************++++KMP+++**********************************/
int kmp(string s0,string t0,int pos)
{
init(s0,t0);
int i=pos,j=1;
while(i<=((int)(s[0]))&&(j<=((int)(t[0]))))
{
if((j==0)||(s[i]==t[j])){++i;++j;}
else j=next[j];
}
if(j>(int)(t[0])) return i-((int)(t[0]));
else return 0;
}
/***************++++INIT+++*****************************************/
void init(string ss,string tt)
{
//cout<<“请输入原串S=: “<<endl;
//cin>>s1;
//cout<<“请输入模式串T=:”<<endl;
//cin>>t1;
s1=ss;
t1=tt;
m=s1.length();
n=t1.length();
//if((s=(char*)malloc((m+1)*sizeof(char)))<0){cout<<“failed\n”;return;}
s=new char[m+1];
s[0]=m;
//if((t=(char*) malloc((n+1)*sizeof(char)))<0) {cout<<“failed\n”;return;}
t=new char[n+1];
t[0]=n;
for(int i=1;i<=m;i++)
s[i]=s1.at(i-1);
for( i=1;i<=n;i++)
t[i]=t1.at(i-1);
cout<<“原串为: “; show(s,m);
cout<<“模式串为: “; show(t,n);
get_next(t,next);
}
/*******************++++SHOW+++**************************************/
void show(char s[],int n )
{
for(int i=1;i<=n;i++)
cout<<s[i]<<” “;
cout<<endl;
cout<<“长度为: “<<int(s[0])<<“\n”;
}