zoukankan      html  css  js  c++  java
  • KMP算法优化

    #include<stdio.h>
    #define MaxSize 255
    typedef struct
    {
    	char ch[MaxSize];
    	int length;
    }SString;
    void InitStr(SString &S)	
    {
    	S.ch[0]=' ';
    	S.length=0;
    }
    void StrCreate(SString &S,char a[])	
    {
    	int i=0,j=1;
    	while(a[i]!='')
    	{
    		S.ch[j++]=a[i++];
    	}
    	S.length=i;
    }
    void get_next(SString T,int next[])		//模式串右移位数
    {
    	int i=1,j=0;
    	next[1]=0;
    	while(i<T.length)
    	{
    		if(j==0 || T.ch[i]==T.ch[j])
    		{
    			i++;j++;
    			next[i]=j;
    		}
    		else
    			j=next[j];
    	}
    }
    void get_nextval(SString T,int nextval[])
    {
    	int i=1,j=0;
    	nextval[1]=0;
    	while(i<T.length)
    	{
    		if(j==0 || T.ch[i]==T.ch[j])
    		{
    			i++;j++;2
    			if(T.ch[i]!=T.ch[j])
    				nextval[i]=j;
    			else
    				nextval[i]=nextval[j];
    		}
    		else
    			j=nextval[j];
    	}
    }
    int Index_KMP(SString S,SString T)		//2.KMP算法优化
    {
    	int i=1,j=1;
    	int next[255];
    	get_nextval(T,next);
    	while(i<=S.length && j<=T.length)
    	{
    		if(j==0 || S.ch[i]==T.ch[j])
    		{
    			i++;j++;
    		}
    		else
    			j=next[j];	//模式串向后移动
    	}
    	if(j>T.length)
    		return i-T.length;
    	else
    		return 0;
    }
    void main()
    {
    	SString S;
    	InitStr(S);
    	char a[]="abcdefg";
    	char b[]="bcd";
    	StrCreate(S,a);
    	SString T;
    	StrCreate(T,b);
    	printf("The T is Num %d in S
    ",Index_KMP(S,T));
    }
    

      

  • 相关阅读:
    [比赛|考试]9.21上午考试
    给花_Q
    [比赛|考试] 9.17下午考试
    [比赛|考试]nowcoder NOIP提高组组第二场
    图论
    生成函数
    P4197 Peaks
    3942: [Usaco2015 Feb]Censoring
    P2245 星际导航
    P3565 [POI2014]HOT-Hotels
  • 原文地址:https://www.cnblogs.com/-slz-2/p/13295490.html
Copyright © 2011-2022 走看看