最近准备自己实现一下AC自动机
先实现一下KMP做准备
KMP网上讲解非常多,就不解释了。
核心思想是一个有限状态自动机,记录匹配的跳转模式,避免了每次匹配失败后回退太多造成浪费。
输入:匹配串,目标串
输出:如果匹配成功,输出第一个匹配成功的索引。如果失败,输出NO.
下面是程序:
#include<iostream> #include<cstring> #include<vector> #include<string> using namespace std; class KMPSearch{ public: static void preKMP(string pattern ,int f[] ){ int m = pattern.length(); int k; f[0] = -1; for(int i=1;i<m;i++){ k = f[i-1]; while(k>=0){ if(pattern[k]==pattern[i-1]) break; else k = f[i]; } f[i] = k+1; } } static int KMP(string pattern , string target){ int m = pattern.length(); int n = target.length(); int* f= new int[m]; preKMP(pattern,f); int i=0; int k=0; while(i<n){ if(k == -1){ i++; k = 0; }else if(target[i] == pattern[k]){ i++; k++; if(k == m) return i - (pattern.length()); }else{ k = f[k]; } } return -1; } static void test(string pat,string tar){ cout<<"模式: "<<pat<<endl; cout<<"语料: " <<tar<<endl; if(KMP(pat,tar)!=-1){ cout<<"YES "<<KMP(pat,tar)<<endl; }else{ cout<<"NO"<<endl; } } }; int main(){ string tar = "san and linux traininglin"; string pat = "lin"; KMPSearch ks; ks.test(pat,tar); getchar(); return 0; }