-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMP.cpp
84 lines (76 loc) · 1.4 KB
/
KMP.cpp
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
#include <bits/stdc++.h>
using namespace std;
int lps[1000002];
// lps[i] holds length of longest proper prefix that is also proper suffix if the string had ended at index i(inclusive).
string pattern,text;
int compute_lps()
{
lps[0]=0;
int i,j;
j=pattern.size();
for(int i=1;i<j;i++)
{
int len = lps[i-1];
while(true)
{
if(len==0)
{
if(pattern[0]==pattern[i])
lps[i] = 1;
else
lps[i] = 0;
break;
}
if(pattern[len]==pattern[i])
{
lps[i] = len + 1;
break;
}
else
{
len = lps[len-1];
}
}
}
}
int kmp()
{
int m=pattern.size(),n=text.size(),i,j=0,val=0;
for(i=0;i<n;)
{
if(text[i]==pattern[j])
{
i++;
j++;
}
else
{
if(j==0)
{
i++;
}
else
{
j=lps[j-1];
}
}
if(j==m)
{
val++;
j=lps[j-1];
}
}
return val;
}
int main()
{
int t,T;
cin>>T;
for(t=1;t<=T;t++)
{
cin>>text>>pattern;
compute_lps();
cout<<"Case "<<t<<": "<<kmp()<<endl;
}
return 0;
}