/*
* =====================================================================================
*
* Filename: kmp.cpp
*
* Description:
*
* Version: 1.0
* Created: 10/14/2012 07:38:59 PM
* Revision: none
* Compiler: gcc
*
* Author: lsff (lsff),
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
void getNext(int *next,char *tr,int n)
{
int i,j;
i=j=0;
next[i]=-1;
while(i<n){
if(j==-1||tr[i]==tr[j]){
++i;++j;
if(tr[i]!=tr[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
}
int getPos(char *src,char *pat,int *next)
{
if(!src||!pat)
return -1;
int slen=strlen(src);
int plen=strlen(pat);
next=new int[plen];
getNext(next,pat,plen);
int i=0,j=0;
while(i<slen&&j<plen){
if(src[i]==pat[j]){
++i;++j;
}
else {
if(j==0) i++;
else
j=next[j-1]+1;
}
}
return j==plen? i-plen :-1;
}
#define maxn 1024
int main()
{
char src[maxn],pat[maxn],c;
bzero(src,sizeof(src));
bzero(pat,sizeof(pat));
int i;
i=0;
while((c=getchar())!='\n') src[i++]=c;
if(c!='\n') while(getchar()!='\n');
i=0;
while((c=getchar())!='\n') pat[i++]=c;
if(c!='\n') while(getchar()!='\n');
int *next;
int index=getPos(src,pat,next);
cout<<index<<endl;
}
kmp 练习下
最新推荐文章于 2021-05-21 21:27:59 发布