#include<stdio.h>
#define N1 11
#define N2 6
void kmp(char *p,char *q,int *next);
void basicIndex(char *p,char *q){
int i=0,j=0,pos;
while(i<N1&&j<N2){
if(p[i]==q[j])
{
i++;
j++;
}else{
i=i-j+1;
j=0;
}
}
if(j>=N2){
pos=i-j;
}else
pos=-1;
printf("%d",pos);
}
//basic next of KMP
void getNext(char *p,char *q){
int i=0,j=-1,next[N2];
next[0]=-1;
while(i<N2){
if(j==-1||q[i]==q[j]){
i++;
j++;
next[i]=j;
}else{
j=next[j];
}
}
kmp(p,q,next);
}
//improved nextvar of KMP
void getNextVar(char *p,char *q){
int i=0,j=-1,nextvar[N2];
nextvar[0]=-1;
while(i<N2){
if(j==-1||q[i]==q[j]){
i++;
j++;
if(q[i]!=q[j]){
nextvar[i]=j;
}else{
nextvar[i]=nextvar[j];
}
}else{
j=nextvar[j];
}
}
kmp(p,q,nextvar);
}
void kmp(char *p,char *q,int *next){
int i=0,j=0,pos=0;
while(i<N1&&j<N2){
if(j==-1||p[i]==q[j]){
i++;
j++;
}else{
j=next[j];
}
}
if(j>=N2){
pos=i-j;
}else{
pos=-1;
}
printf("%d",pos);
}
void main(){
char *p={"00000000001"};
char *q={"000001"};
getNext(p,q);
}
字符串的模式匹配算法
最新推荐文章于 2020-05-23 15:59:12 发布