串的模式匹配算法 窮舉與KMP

 
//窮舉算法
#include <stdio.h>
#include <stdlib.h>
const int maxLen=128;
typedef struct String
{
    int curLen;
    char *ch;
    int f[];
}String;
int fastFind(String Tar,String Pat)
{
    int posP=0,posT=0;
    int lengthP=Pat.curLen,lengthT=Tar.curLen;
    while(posP<lengthP&&posT<lengthT)
    {
        if(Pat.ch[posP]==Tar.ch[posT])
        {
            posP++;posT++;
        }
        else if(posP==0) posT++;
        else posP==Pat.f[posP-1]+1;
    } 
    if(posP<lengthP) return -1;
    else return posT-lengthP;       
}
void fail(String Pat)
{
    int lengthP=Pat.curLen;
    int j=1;
    Pat.f[0]=-1;
    printf("%d ",Pat.f[0]);
    for(j=1;j<lengthP;j++)
    {
        int i=Pat.f[j-1];
        printf("%c ",*(Pat.ch+j));
        printf("%c ",*(Pat.ch+i+1));
        while((*(Pat.ch+j)!=*(Pat.ch+i+1))&&(i>=0))
              i=Pat.f[i];
        if(*(Pat.ch+j)==*(Pat.ch+i+1))
             Pat.f[j]=i+1;
        else
              Pat.f[j]=-1;
        printf("%d  ",Pat.f[j]);
    }
}
int main(int argc, char *argv[])
{
  String Tar,Pat;
  char T[maxLen],P[maxLen];
  int position;
  printf("輸入目標串(長度小於等於128)");
  gets(T);Tar.ch=T;Tar.curLen=strlen(T);
  printf("輸入模式串(長度小於等於128)");
  gets(P);Pat.ch=P;Pat.curLen=strlen(P);fail(Pat);
  position=fastFind(Tar,Pat);
  printf("模式串在目標串的起始位置爲:");
  printf("%d",position); 
  system("PAUSE");	
  return 0;
}

//KMP算法
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct String
{
    int curLen;
    char *ch;
    int f[];
}String;
int fastFind(String Tar,String Pat)
{
    int posP=0,posT=0;
    int lengthP=Pat.curLen,lengthT=Tar.curLen;
    while(posP<lengthP&&posT<lengthT) //目標和模式指針都沒指到最後
    {
        if(Pat.ch[posP]==Tar.ch[posT])
        {
            posP++;posT++;       //若相等則繼續比較
        }
        else if(posP==0) posT++;   //第一個字符不相等,目標指針加1
        else posP=Pat.f[posP-1]+1;  //模式指針右移
    } 
    if(posP<lengthP) return -1;     //匹配失敗
    else return posT-lengthP;         //匹配成功,返回存儲位置
}
void fail(String Pat)
{
    int lengthP=Pat.curLen;
    int j=1;
    Pat.f[0]=-1;                  //直接賦值
   // printf("%d ",Pat.f[0]);
    for(j=1;j<lengthP;j++)             //依次求f [j]
    {
        int i=Pat.f[j-1];
       // printf("%c ",*(Pat.ch+j));
      //  printf("%c ",*(Pat.ch+i+1));
        while((*(Pat.ch+j)!=*(Pat.ch+i+1))&&(i>=0))
              i=Pat.f[i];             //遞推
        if(*(Pat.ch+j)==*(Pat.ch+i+1))
             Pat.f[j]=i+1;
        else
              Pat.f[j]=-1;
     //   printf("%d  ",Pat.f[j]);
    }
}
int main(int argc, char *argv[])
{
  String Tar,Pat;
  char T[128],P[128];
  int position;
  printf("輸入目標串(長度小於等於128)");
  gets(T);Tar.ch=T;Tar.curLen=strlen(T);
  printf("輸入模式串(長度小於等於128)");
  gets(P);Pat.ch=P;Pat.curLen=strlen(P);fail(Pat);
  position=fastFind(Tar,Pat);
  printf("模式串在目標串的起始位置爲:");
  printf("%d",position); 
  system("PAUSE");	
  return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章