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;
    }
    int Index(SString S,SString T)		//1.简单模式匹配
    {
    	int i,k,j;
    	k=1;i=k;j=1;
    	while(i<S.length && j<T.length)
    	{
    		if(S.ch[i]==T.ch[j])
    		{
    			i++;j++;
    		}
    		else		//匹配失败,主串模式串皆回退重新匹配
    		{
    			k++;
    			i=k;
    			j=1;
    		}
    	}
    	if(j>=T.length)
    		return k;
    	else 
    		return 0;
    }
    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];
    	}
    }
    int Index_KMP(SString S,SString T)		//2.KMP算法
    {
    	int i=1,j=1;
    	int next[255];
    	get_next(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(S,T));
    	printf("The T is Num %d in S
    ",Index_KMP(S,T));
    }
    

      

  • 相关阅读:
    九省联考2018 IIIDX
    WC2020 猜数游戏
    Gym101821D Search Engine
    Gym102586B Evacuation
    Gym102576D Clique
    UOJ498 新年的追逐战
    LOJ6703 小 Q 的序列
    Codechef A Leisurely Journey
    LG5050 多项式多点求值 和 LG5158 多项式快速插值
    PE427 n-sequences 和 ZJOI2020 抽卡
  • 原文地址:https://www.cnblogs.com/-slz-2/p/13295352.html
Copyright © 2011-2022 走看看