1、
KMP算法是一种线性时间复杂的字符串匹配算法,它是对BF算法(Brute-Force,最基本的字符串匹配算法的)改进。
对于给的的原始串S和模式串P,需要从字符串S中找到字符串P出现的位置的索引。
BF算法的时间复杂度O(strlen(S) * strlen(T)),空间复杂度O(1)。
KMP算法的时间复杂度O(strlen(S) + strlen(T)),空间复杂度O(strlen(T))。
2、
一个KMP算法,说白了就是构造最大后缀长度数组。
KMP算法与BF算法的区别在于,字符串失配时的处理。
KMP利用之前已经匹配好的位置,将字符串的移动次数降低,移动的步子增大。
3、
#include <iostream>
#include <string>
using namespace std;
int kmp_find(const string& target,const string& pattern)
{
const int pattern_length = pattern.size();
const int target_length = target.size();
int *overlay_function = new int [pattern_length];
int index;
overlay_function[0] = -1;
for(int i = 1; i< pattern_length; i++)
{
index = overlay_function[i-1];
while(index >= 0 && pattern[i] != pattern[index+1] )
{
index = overlay_function[index];
}
if(pattern[i] == pattern[index+1])
{
overlay_function[i] = index+1;
}
else
overlay_function[i] = -1;
}
//match algrithm start
int target_index=0;
int pattern_index=0;
while(target_index < target_length&& pattern_index < pattern_length)
{
if(target[target_index] ==pattern[pattern_index])
{
++target_index;
++pattern_index;
}
else if(pattern_index == 0)
{
++target_index;
}
else
{
pattern_index = overlay_function[pattern_index-1] + 1;
}
}
delete [] overlay_function;
if(pattern_index == pattern_length)
return target_index - pattern_length;
else
return -1;
}
void main()
{
string source = "asdsdadwridisdaabaabcabacsdshdsads";
string pattern = "abaabcabac";
cout<<kmp_find(source,pattern)<<endl;
}