【笔记】大话数据结构-KMP算法

#include <stdio.h>

/*
	计算next数组 
*/ 
void get_next(char *T , int *next)
{
    
    
	int i,j;
	i=1;
	j=0;
	next[0]= 0; 
	while(i<strlen(T)) //T[0]是串T的长度 
	{
    
    
		if(j==0 || T[i-1] == T[j-1]) //T[i]表示后缀 T[j]表示前缀 
		{
    
    
			i++;
			j++;
			next[i]=j;
		}
		else j=next[j];
	}
	for(i=0;i<=strlen(T);i++){
    
    
	printf("%d\n",next[i]);
	}
}
/*
	改进版 
*/ 
void Next(char*T,int *next){
    
    
    int i=1;
    next[1]=0;
    int j=0;
    while (i<strlen(T)) {
    
    
        if (j==0||T[i-1]==T[j-1]) {
    
    
            i++;
            j++;
            if (T[i-1]!=T[j-1]) {
    
    
               next[i]=j;
            }
            else{
    
    
                next[i]=next[j];
            }
        }else{
    
    
            j=next[j];
        }
    }
}
 
int Index_KMP(char *S,char *T)
{
    
    
	int i=1;
	int j=1;
	int next[255];
	get_next(T,next);
	while(i<=strlen(S)&&j<=strlen(T)){
    
    
		if(j==0||S[i-1]==T[j-1])
		{
    
    
			i++;
			j++;
		}
		else
		{
    
    
			j=next[j];
		}
	}
	
	if(j>strlen(T)) return i-(int)strlen(T);
	else return 0;
}

int main()
{
    
    
	int k=Index_KMP("ababcabcacbab","abcac");
	printf("%d",k);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/Ethan_997/article/details/108451984