KMP算法

#include "stdio.h"
#include "stdlib.h"
#include "iostream.h"
#define TRUE  1
#define FALSE  0
#define OK  1
#define ERROR  0
#define INFEASLBLE  -1
#define OVERFLOW  -2
#define MAXSTRLEN  255      //用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1]; //0号单元存放串的长度
 
// 求模式串T的next函数值并存入数组next
void get_next(SString T,int next[])
{
   int i=0,j=1;
   next[1]=0;
   while(i
    if(j==0||T[i]==T[j]){
        i++;
        j++;
        next[i]=j;
    }
    else
       j=next[j];
   }
}
 
//KMP算法
// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置
int Index_KMP(SString S,SString T,int pos)
{
     int i=pos,j=1;
      while(i
        if(j==0||S[i]==T[j]){
            i++;
            j++;
        }
        else
            j=next[j];
      }
       if(j>T[0])
        return i-T[0];
       else
        return 0;
}
 
---------------------------------------------------------
//如数组零号单元不存字符个数而用来存字符元素,则为
void get_next(SString T,int next[])    //求next数组
{
   int i=0,j=-1;
   next[0]=-1;
   m=srelen(S);
   while(i
    if(j==-1||T[i]==T[j]){
        i++;
        j++;
        next[i]=j;
    }
    else
       j=next[j];
   }
}
 
//KMP算法
// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置
int Index_KMP(SString S,SString T,int pos)
{
     int i=pos,j=0;
     m=srelen(S);
     n=srelen(T);
     while(i
        if(j==-1||S[i]==T[j]){
            i++;
            j++;
        }
        else
            j=next[j];
      }
       if(j>m)
        return i-m;
       else
        return -1;
}
-----------------------------------------------------------
//主函数
void main()
{
    SString T,S;
    int i,j,n;
    char ch;
    int pos;
    scanf(“%d”,&n);    // 指定n对需进行模式匹配的字符串
    ch=getchar();
    for(j=1; j<=n; j++)
    {
        ch=getchar();
        for( i=1; i<=MAXSTRLEN&&(ch!='\n'); i++)  // 录入主串
        {
            S[i]=ch;
            ch=getchar();
        }
        S[0]=i-1;    // S[0]用于存储主串中字符个数
        ch=getchar();
        for( i=1; i<=MAXSTRLEN&&(ch!='\n'); i++)  // 录入模式串
        {
            T[i]=ch;
            ch=getchar();
        }
        T[0]=i-1;    // T[0]用于存储模式串中字符个数
        pos=Index_KMP( S, T,pos) ;    // 请填空
        printf("%d\n",pos);
    }
}

posted on 2016-05-07 00:50  yujon  阅读(281)  评论(0编辑  收藏  举报

导航