C++实现——KMP匹配算法
#include<iostream>
using namespace std;
void compute_prefix(string& str, int next[]);
int kmp_matcher(string& str, string& pat);
int main()
{
string s1 = "ababababccascb";
string p1 = "abc";
cout << kmp_matcher(s1, p1);
return 0;
}
void compute_prefix(string& str, int next[])
{
int len = str.size();
next[0] = 0;
int j = 0;
for (int i = 1; i < len; i++)
{
while(j>0&&str[i] != str[j])
j = next[j];
if(str[i]==str[j])
j = j + 1;
next[i] = j;
}
}
int kmp_matcher(string& str, string& pat)
{
int pat_len = pat.size();
int* next = new int[pat_len];
compute_prefix(pat, next);
int j = 0;
for (int i = 0; i < str.size(); i++)
{
while (j > 0 && str[i] != pat[j])
j = next[j];
if (str[i] == pat[j])
j++;
if (j == pat_len)
return i - j + 1;
}
delete[] next;
return -1;
}