-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathKnuthMorrisPratt.cpp
More file actions
91 lines (87 loc) · 1.13 KB
/
KnuthMorrisPratt.cpp
File metadata and controls
91 lines (87 loc) · 1.13 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define mp make_pair
#define pb push_back
#define mt make_tuple
#define LD long double
#define gc getchar_unlocked
#define pc putchar_unlocked
#define MOD 1000000007
#define MAXN 2*100005
#define bitcount __builtin_popcount
#define INF 2000000000
#define EPS 1e-9
template<typename T>T absll(T X)
{
if(X<0)
return -1*X;
else
return X;
}
vector<int> KMP_Prefix(string P)
{
int M=P.size();
vector<int> lps(M,0);
int i=0,j=1;
lps[0]=0;
while(j<M)
{
if(P[i]==P[j])
{
i++;
lps[j]=i;
j++;
}
else
{
if(i!=0)
{
i=lps[i-1];
}
else
{
lps[j]=0;
++j;
}
}
}
return lps;
}
void KMP_Search(string T,string P)
{
vector<int> lps=KMP_Prefix(P);
int i=0,j=0;
int N=T.length();
int M=P.length();
while(i<N)
{
if(P[j]==T[i])
{
i++;
j++;
}
if(j==M)
{
printf("Shift occurs at %d\n",i-j);
j=lps[j-1];
}
else if(i<N&&P[j]!=T[i])
{
if(j!=0)
{
j=lps[j-1];
}
else
{
i++;
}
}
}
}
int main()
{
KMP_Search("ABABDABACDABABCABAB","ABABCABAB");
cout<<endl;
return 0;
}