-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKMP.cpp
More file actions
47 lines (47 loc) · 719 Bytes
/
KMP.cpp
File metadata and controls
47 lines (47 loc) · 719 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
bool KMP(const string &text, const string &pat)
{
vector<int> lps(pat.length(),0);
int i = 1,j = 0;
while(i < pat.length())
{
if(pat[i] == pat[j])
lps[i++] = ++j;
else
{
if(j!=0)
j = lps[j-1];
else
lps[i++] = 0;
}
}
i = 0,j = 0;
while(i < text.length() && j < pat.length())
{
if(text[i] == pat[j])
{
i++;
j++;
}
else
{
if(j != 0)
{
j = lps[j-1];
}
else
i++;
}
}
return (j == pat.length());
}
int main()
{
string text = "abcxabcdabcdabcy";
string pattern = "abcdabcy";
bool res = KMP(text,pattern);
if(res) cout << "Pattern found in text";
else cout << "Pattern not found in text";
}