KMP算法

KMP板子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* @Author: onlooker
* @Date: 2020-03-07 11:28:45
* @LastEditTime: 2020-09-06 10:42:32
* @FilePath: \code\test.cpp
*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define maxn 15
int nextt[maxn]={0};
void getnext(string b){
nextt[0]=-1;
int i=0,j=-1;
int m=b.size();
while(i<m){
if(j==-1||b[i]==b[j]){
i++;j++;
nextt[i]=j;
}
else{
j=nextt[j];
}
}
}
int kmp(string a,string b)
{
int i=0,j=0;
int n=a.size(),m=b.size();
while(i<n&&j<m){
if(a[i]==b[j]||j==-1){
i++;j++;
}
else{
j=nextt[j];
}
}
if(j==m){
return i-j;
}
else{
return -1;
}
}
int main()
{
string a,b;
cin>>a>>b;
getnext(b);
int ans=-1;
ans=kmp(a,b);
if(ans!=-1){
cout<<"find from "<<ans<<" to "<<ans+b.size()-1<<endl;
}
else{
cout<<"not found"<<endl;
}
return 0;
}