-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKMP.cpp
More file actions
52 lines (52 loc) · 998 Bytes
/
Copy pathKMP.cpp
File metadata and controls
52 lines (52 loc) · 998 Bytes
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
#include <bits/stdc++.h>
#define N 1000000009
#define M 1000000
using namespace std;
typedef long long int lli;
int *KMPpreprocess(string P)
{
int l=P.length();
int *F=(int *)malloc((l+1)*sizeof(int));
F[0]=-1;
int i=0,j=-1;
while(i<l)
{
while(j>=0&&P[i]!=P[j])
j=F[j];
i++;j++;
F[i]=j;
}
return F;
}
void KMP(string P,string T)
{
int *F=KMPpreprocess(P);
int l1=P.length();
int l2=T.length();
/*for(int i=0;i<=l1;i++)
cout<<F[i]<<" ";
cout<<endl;*/
int i=0,j=-1;
while(i<l2)
{
while(j>=0&&T[i]!=P[j])
j=F[j];
i++;j++;
//cout<<j<<endl;
if(j==l1)
{
printf("Pattern Found at %d index\n",i-j);
j=F[j];
}
}
free(F);
}
int main()
{
string T,P;
cout<<"Enter Text"<<endl;
cin>>T;
cout<<"Enter Pattern"<<endl;
cin>>P;
KMP(P,T);
}