#include <iostream>
#include <cstring>
using namespace std;
void kmp_t(const char * s, int *t)
{
int len = strlen(s);
if(len<=2){
t[0]=-1; t[1]=0;
}
else{
t[0]=-1; t[1]=0;
int temp1,temp2;
temp1 = 2; temp2 = 0;
while(temp1<len){
if(s[temp1-1] == s[temp2]){
temp2++;
t[temp1] = temp2;
temp1++;
}
else if(temp2)
temp2 = t[temp2];
else{
t[temp1] = 0;
temp1++;
}
}
}
for(int i=0;i<len;i++)
{
cout<<s[i]<<" "<<t[i]<<endl;
}
}
int kmp(const char * s1, const char *s2, int *t){
int len1 = strlen(s1);
int len2 = strlen(s2);
int m1=0, m2=0;
while(m1+m2<len1){
cout<<m1<<" "<<m2<<endl;
if(s1[m1+m2] == s2[m2]){
m2++;
if(m2>=len2){return m1;}
}
else{
if(t[m2]==-1){
m1 += 1;
m2 = 0;
}
else{
m1 += m2-t[m2];
m2 = t[m2];
}
}
}
return -1;
}
int main()
{
const char *s1; s1 = "ababctabfdabababcdab";
const char *s2; s2 = "ababcd";
int *t = new int[strlen(s2)];
int n_start;
fill(t,t+strlen(s2),0);
kmp_t(s2,t);
n_start = kmp(s1,s2,t);
cout<<n_start<<endl;
for(int i=0; i<strlen(s1); i++)
{
if(i==n_start)cout<<" || ";
if(i==n_start+strlen(s2))cout<<" || ";
cout<<s1[i]<<" ";
}
return 0;
}
算法1:字符串模式匹配KMP算法 源代码
原文作者:KMP算法
原文地址: https://blog.csdn.net/zhoudi2010/article/details/52304046
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/zhoudi2010/article/details/52304046
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。