[C++]KMP算法实现
#include<string>
using namespace std;
class KMP
{
public:
KMP(string);
int search(string txt);
private:
string pat;
static const int R = 256;
int* dfa[R];
int M;
};
KMP::KMP(string _pat)
{
pat = _pat;
M = pat.length();
for (int i = 0; i < R; i++){
dfa[i] = new int[M];
for (int j = 0; j < M; j++){
dfa[i][j] = 0;
}
}
dfa[pat[0]][0] = 1;
for (int X = 0, j = 1; j < M; j++){
for (int c = 0; c < R; c++){
dfa[c][j] = dfa[c][X];
}
dfa[pat[j]][j] = j + 1;
X = dfa[pat[j]][X];
}
}
int KMP::search(string txt){
int i, j;
int N = txt.length();
for (i = 0, j = 0; i < N&&j < M; i++){
j = dfa[txt[i]][j];
}
if (j == M) //如果找到返回在txt中的位置
return i - M;
else //找不到则返回txt的长度
return N;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。