最难理解的是KMP算法,费了好大劲才弄明白。
要理解KMP算法,其实最关键的是生成标明下次匹配位置的next[]数组。其意义是,如果当前匹配到模式字符串的第j个字符是失配,则只需要将j重置为next[j]后,继续向后匹配即可。
next[j]的值表示P[0...j-1]中最长后缀的长度等于相同字符序列的前缀, 假设next[j]=k, 即P[0...k-1]==P[j-k,j-1]
参考:http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html
下面是几处关键代码的说明:
92.next_value[index]=j;//模式字符串从头自匹配到此为止
94.next_value[index]=next_value[j];//当前位置仍然匹配,递归赋值
98.j=next_value[j];//上次失配,这次重置j
#include "iostream"
#include "vector"
#include "string"
using namespace std;
bool BF_Match(string to_be_matched,string pattern);
void getNextVal(string pattern,int *next_value);
bool KMP_Match(string to_be_matched,string pattern);
int main()
{
string long_str("ababaababc");
string pattern_str("ababc");
//bool isMatch=BF_Match(long_str,pattern_str);
bool isMatch=KMP_Match(long_str,pattern_str);
if(isMatch)
cout<<"matching success!"<
-1&&pattern[j+1]!=pattern[i])
j=next_value[j];
if(pattern[i]==pattern[j+1])
++j;
next_value[i]=j;
}
}