KMP

KMP这个代码的复杂度是n+m的,但是蛮力法的复杂度是n^2,所以还是提高了

至于为啥是叫kmp,因为是三个人共同提出的这个算法,将他们三个人的姓氏的首字母合在一起,就叫了这个名字KMP。

kmp看懂了,但是代码还是不熟练,需要继续巩固,这个代码的理解花了好几个小时,主要参考了两个网站,

https://www.cnblogs.com/zhangtianq/p/5839909.html  这个网站理解了kmp的思想,然后看了半天的next数组还是不会

于是就去找了另一个网站看next数组怎么算, https://blog.csdn.net/yutong5818/article/details/81319120  于是参考了这个文章的黑体字部分,理解了next数组怎么求,以及他的意义,这也是kmp代码的核心,也是难点所在。

//date:2020.4.19
//参考链接 https://blog.csdn.net/yutong5818/article/details/81319120
#include <bits/stdc++.h>
using namespace std;
void calnext(char s[],int next[])
{
int k=0;
next[0]=0;
for(int i=1; i<strlen(s); i++)
{
while(k>0&&s[i]!=s[k])
k=next[k-1];
if(s[i]==s[k])
k++;
next[i]=k;
}
}
int kmp(char pipei[],char daipipei[])
{
int len1=strlen(pipei);
int len2=strlen(daipipei);
int next[len2];
calnext(daipipei,next);
for(int i=0,j=0; i<len1; i++)
{
while(j>0&&pipei[i]!=daipipei[j])
j=next[j-1];
if(pipei[i]==daipipei[j])
j++;
if(j==len2)
return i-j+1;
}
}
int main()
{
char t[]="123614561123458412";
char s[]="611";
cout<<t<<endl;
cout<<s<<endl;
int res=kmp(t,s);
cout<<"下标为"<<res<<endl;
return 0;
}

 

posted @ 2020-04-19 16:28  someonezero  阅读(152)  评论(0编辑  收藏  举报