学过数据结构的人,都对KMP算法印象颇深。尤其是新手,更是难以理解其涵义,搞得一头雾水。
严老的《数据结构》79-84页讲了基本的匹配方法,这是基础。先把这个搞懂了。 80页在讲KMP算法的开始先举了个例子,让我们对KMP的基本思想有了最初的认识。目的在于指出“由此,在整个匹配的过程中,i指针没有回溯,”。
今天闲着没事干,实现了一下这个算法,不得不感叹,发明这些算法的前辈实在太牛了,向你们致敬!#include <iostream>
#include <string>
using namespace std;
void get_next(const string &T, int next[])
{
next[0] = -1;
int k = 0, j = -1;
while (k != T.size()) //k遍历一次整个子串T
{
if (-1 == j || T[k] == T[j]) //j回溯到了起点 或者 T[k]等于T[j]
{
++k;
++j;
if (T[k] == T[j]) //相等的话赋同样的值
{
next[k] = next[j];
}
else
{
next[k] = j;
}
}
else
{
j = next[j]; //否则j回溯
}
}
}
int KMP(const string &S, const string &T)
{
int i = 0, j = 0;
int *next = new int[T.size()+1];
get_next(T, next); //获得next数组的值以便于j的回溯
while (i != S.size() && j != T.size())
{
if (-1 == j || S[i] == T[j]) //j在起始位置或者相等就继续往后移
{
++i;
++j;
}
else
{
j = next[j]; //否则j回溯
}
}
delete []next;
if (T[j] == '/0')
{
return i - j;
}
else
{
return -1;
}
}
int main()
{
string S = "ababcabcacbab", T = "abcac";
cout << KMP(S, T) << endl;
return 0;
}
本文摘自: 编程十万个为什么(http://www.bcwhy.com) 详细出处请参考:http://www.bcwhy.com/thread-1771-3-1.html