-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathKMPalgorithm.cpp
More file actions
110 lines (93 loc) · 1.8 KB
/
KMPalgorithm.cpp
File metadata and controls
110 lines (93 loc) · 1.8 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
Finding pattern in string using KMP Algorithm
Given two strings P ans S consisting of lowercase english letters, find whether P is preent in S as a substring or not.
Input format :
First and only line of Input contains two space separated strings P and S consisting of only lowercase english letters.
Output format :
For each input print YES if string P is present in string S ,otherwise NO.
*/
#include<bits/stdc++.h>
using namespace std;
void Prefix_array(string p, vector<int> &lps)
{
int len = 0;
int index = 1;
int m = p.size();
while (index < m)
{
if (p[index] == p[len])
{
len += 1;
lps[index] = len;
index += 1;
}
else
{
if (len == 0)
{
lps[index] = 0;
index += 1;
}
else
{
len = lps[len - 1];
}
}
}
}
void code()
{
string p,s;
cin>>p>>s;
int m = p.size();
int n = s.size();
vector<int> lps(m, 0);
Prefix_array(p, lps);
int index1 = 0;
int index2 = 0;
while (index1 < n)
{
if (s[index1] == p[index2])
{
index2++;
index1++;
if (index2 == m)
{
cout<<"YES"<<endl;
return;
}
if (index1 == n)
{
cout<<"NO"<<endl;
return;
}
}
else
{
if (index2 == 0)
{
index1 += 1;
}
else
{
index2 = lps[index2 - 1];
}
}
}
cout<<"NO"<<endl;
return;
}
int main(){
code();
}
/*
Input:
3
xxy yxxyxxy
a baac
cfg cgfgfc
Output:
YES
YES
NO
*/