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));
    }
    

      

  • 相关阅读:
    清理yum源
    XZ压缩
    Linux命令之dot
    calltree查看工程代码中的函数调用关系
    valgrind 打印程序调用树+进行多线程性能分析
    LINUX 性能 测试 优化工具
    TCP/IP(84) 详解
    perf---LINUX内核研究
    廖雪锋笔记3:类型转换
    廖雪锋笔记2:list,tuble
  • 原文地址:https://www.cnblogs.com/-slz-2/p/13295490.html
Copyright © 2011-2022 走看看