其算法复杂度为两个字符串的长度之和(m+n)。
与C语言版本想比,这个版本只是使用C++语法,功能还是被封装在函数中。
#include#include #include #include using namespace std;inline void NEXT(const string &T, vector &next){ //按模式串生成vector,next(T.size()) next[0]=-1; for(int i=1; i = 0) j = next[j];//递推计算 if(T[i] == T[j+1]) next[i] = j+1; else next[i] = 0; }}inline string::size_type COUNT_KMP(const string &S, const string &T){ //利用模式串T的next函数求T在主串S中的个数count的KMP算法 //其中T非空, vector next(T.size()); NEXT(T, next); string::size_type index, count=0; for(index=0; index