-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathKMP Pattern Search-gfg-Siddhartha-Agarwal.cpp
105 lines (82 loc) · 1.67 KB
/
KMP Pattern Search-gfg-Siddhartha-Agarwal.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// { Driver Code Starts
//Initial Template for C++
// C++ program for implementation of KMP pattern searching
// algorithm
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
// Fills lps[] for given patttern pat[0..M-1]
void computeLPSArray(string s, int M, int* lps)
{
int n=s.length();
lps[0]=0;
int len=0;
for(int i=1;i<n;)
{
if(s[len]==s[i])
{
lps[i]=++len;
i++;
}
else if(len==0)
{
lps[i]=0;
i++;
}
else
{
len=lps[len-1];
}
}
}
// Returns true if pat found in txt
bool KMPSearch(string pat, string txt) {
// Your code here
int i=0, j=0;
int n=txt.length(),m=pat.length();
int lps[txt.length()];
computeLPSArray(pat,pat.length(),lps);
while(i<n)
{
if(pat[j]==txt[i])
{
i++;
j++;
}
if(j==m)
{
return true;
j=lps[j-1];
}
if(pat[j]!=txt[i])
{
if(j==0)
{
i++;
}
else
{
j=lps[j-1];
}
}
}
return false;
}
// { Driver Code Starts.
// Driver program to test above function
int main()
{
int t;
std::cin >> t;
while(t--){
string s, pat;
cin >> s >> pat;
if(KMPSearch(pat, s)){
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
return 0;
}
// } Driver Code Ends