-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathkmp.cpp
More file actions
65 lines (60 loc) · 1.14 KB
/
kmp.cpp
File metadata and controls
65 lines (60 loc) · 1.14 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
#include <bits/stdc++.h>
using namespace std;
vector<int> calculateLPS(string pat)
{
int n = pat.size();
vector<int> LPS(n);
LPS[0] = 0;
int j = 1, i = 0;
while (i < n && j < n)
{
if (pat[i] == pat[j])
{
LPS[j] = i + 1;
i++;
j++;
}
else
{
if (i != 0)
i = LPS[i - 1];
else
{
LPS[j] = 0;
j++;
}
}
}
return LPS;
}
int KMPSearch(string pat, string txt)
{
vector<int> LPS = calculateLPS(pat);
//LPS[i] = where to start mathcing in pat after a mismatch at pos i+1
int i = 0, j = 0;
int n = txt.size(), m = pat.size();
while (i < n)
{
if (txt[i] == pat[j])
{
i++, j++;
}
else
{
if (j > 0)
j = LPS[j - 1];
else
i++;
}
if (j == m)
return (i - j);
}
return -1;
}
int main()
{
string txt = "hello";
string pat = "ll";
cout << "Found at " << KMPSearch(pat, txt);
return 0;
}