今天下午实现了KMP算法
这个算法算是奇妙,本机器看了10遍左右才基本理解
算法的核心就是求出next,再依次根据next跳转,这样就能线性地匹配出字符串
这里推荐一篇博文http://blog.csdn.net/joylnwang/article/details/6778316,joylnwang说得很好,深入浅出,只是在next数组是从1开始的,而pattern是从0起始,这也算是前几次学习的时候没有理解的地方
今天下午写的代码也应用了template,也能兼容其他的数据类型,练习了一下C++
<pre name="code" class="cpp">#include "iostream"
#include "string"
using namespace std;
template <class T>
class KPM
{
private:
int MAX_P;
int MAX_T;
int *next = new int[MAX_P + 1];
T *pattern = new T[MAX_P + 1];
T *target = new T[MAX_T];
int* BuildNext();
public:
KPM(T *pat, int max_p, T *tar , int max_t)
{
MAX_P = max_p;
MAX_T = max_t;
pattern = pat;
target = tar;
}
int GetResult();
};
template <class T>
int* KPM<T>::BuildNext()
{
int i = 1;
int t = 0;
next[i] = 0;
while (i < MAX_P)
{
while (t > 0 && pattern[i - 1] != pattern[t-1])//依次向前找到next,确定f(t)
{
t = next[t];
}
++t;
++i;
if (pattern[i - 1] == pattern[t - 1])
{
next[i] = next[t];
}
else
{
next[i] = t;
}
}
for (int i = 1; i < MAX_P +1 ; i++)
{
cout << next[i] << " ";
}
cout << endl;
return next;
}
template <class T>
int KPM<T>::GetResult()
{
BuildNext();
int t = 0;
int p = 0;
while (t < MAX_T && p < MAX_P + 1)
{
if (p == 0 || target[t] == pattern[p - 1])
{
cout << target[t] << " " << t << " " << pattern[p] << " " << p << endl;
++t;
++p;
}
else
{
p = next[p];
}
}
if (p == MAX_P + 1)
{
cout << "从主串的第" << t - MAX_P + 1 << "个数开始匹配" << endl;
return t - MAX_P;
}
else
{
cout << "主串无可匹配的子串" << endl;
return 0;
}
}
int main()
{
char *P = "abcabcacab";
char *T = "babcbabcabcaabcabcabcacabc";
KPM<char> *a = new KPM<char>(P, 10, T, 26);
a -> GetResult();
system("pause");
}