模式匹配---KMP算法

//KMP算法的效率主要是去掉了指針回溯,藉助於實效函數,可以高效的移動指針到下一個檢查位置

#include <string>
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;

void fail(char *src, int *f);
int KmpFind(char *src, char *pat, int fail[]);

int main()
{
 char src[100], pat[100];
 int f[100],pos;
 cout<<"輸入原字符串:"<<endl;
 cin.getline(src,100);
 cout<<"輸入子串:"<<endl;
 cin.getline(pat,100);
 fail(src,f);
 pos = KmpFind(src,pat,f);
 if(pos == -1) cout<<src<<" 中沒有 "<<pat<<" 子串 "<<endl;
 else cout<<src<<" 中子串 "<<pat<<" 起始位置爲: "<<pos<<endl;
 getch();
 return 0;
}

void fail(char *src , int *f)//src爲原字符串,f[]爲失效函數
{
 int lengthP = strlen(src);
 f[0] = -1;
 for(int j = 1; j < lengthP; j++)
 {
  int i = f[j-1];
  while(*(src + j) != *(src + i + 1) && i >= 0) i = f[i];
  if(*(src +j) == *(src + i + 1)) f[j] = i + 1;
  else f[j] = -1;
 }
}


int KmpFind(char *src, char *pat, int fail[])//fail[]爲失效函數
{
 int posP = 0, posT = 0;
 int lengthP = strlen(pat), lengthT = strlen(src);
 while(posP < lengthP && posT < lengthT)
 {
  if(pat[posP] == src[posT])
  {
   posP++;
   posT++;
  }
  else if(posP == 0)
  {
   posT++;
  }
  else posP = fail[posP - 1] + 1;
 }
 if(posP < lengthP)
  return -1;
 else return posT - lengthP + 1;
}


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