kmp
简略的写了一个,可能有问题,之后学习编译原理的时候应该会使用,到时候在修改。
kmp.h
#include <string> using namespace std; class Kmp { private: string modelstr; string mainstr; int *next; bool findnext(); public: Kmp(const string& modstr,const string& mnstr); ~Kmp(); void shownext(); int substr(); };
kmp.cpp
#include "kmp.h" #include <iostream> using namespace std; Kmp::Kmp(const string& modstr,const string& mnstr):modelstr(modstr),mainstr(mnstr) { next=new int[modelstr.length()]; findnext(); } Kmp::~Kmp() { delete []next; } bool Kmp::findnext() { unsigned s=0,t=0; if(!next) return false; next[0]=0; for(s=1,t=0;s<modelstr.length();s++) { while(t>0&&modelstr[s]!=modelstr[t]) t=next[t-1]; if(modelstr[s]==modelstr[t]) { t++; next[s]=t; } else next[s]=0; } return true; } int Kmp::substr() { unsigned s=0,i=0; //i是文本串指针,s是模式串指针; if(!next) return -1; for(i=0,s=0;i<mainstr.length();i++) { while(s>0&&mainstr[i]!=modelstr[s]) s=next[s-1]; if(mainstr[i]==modelstr[s]) s++; if(s==modelstr.length()) return i-s+1; } return -1; } void Kmp::shownext() { int i=0; for(i=0;i<modelstr.length();i++) cout<<next[i]<<' '; }
main.cpp
#include <iostream> #include <string> #include "kmp.h" using namespace std; int main(void) { string modstr="hehe"; string mnstr="sssdfefxhehe"; Kmp kmp(modstr,mnstr); cout<<kmp.substr()<<endl; kmp.shownext(); return 0; }