-
Notifications
You must be signed in to change notification settings - Fork 0
/
Knuth–Morris–Pratt algorithm(KMP).cpp
84 lines (81 loc) · 1.48 KB
/
Knuth–Morris–Pratt algorithm(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;
#define MAX 100005
int failure[MAX];
void build_failure_function(string pattern, int m)
{
failure[0] = 0;
failure[1] = 0;
for(int i = 2; i <= m; i++)
{
int j = failure[i - 1];
while(true)
{
if(pattern[j] == pattern[i - 1])
{
failure[i] = j + 1;
break;
}
if(j == 0)
{
failure[i] = 0;
break;
}
j = failure[j];
}
}
}
bool kmp(string text, string pattern)
{
int n = text.size();
int m = pattern.size();
build_failure_function(pattern, m);
int i = 0;
int j = 0;
while(true)
{
if(j == n)
{
return false;
}
if(text[j] == pattern[i])
{
i++;
j++;
if(i == m)
{
return true;
}
}
else
{
if (i == 0)
{
j++;
}
else
{
i = failure[i];
}
}
}
return false;
}
int main()
{
string s, s2;
int t,n, m, q, i, j;
cin >> t;
while(t--){
cin >> s >> q;
for(i=0; i<q; i++){
cin >> s2;
if(kmp(s, s2)){
cout << "y"<< endl;
}
else
cout << "n"<< endl;
}
}
return 0;
}