This repository has been archived by the owner on Nov 21, 2020. It is now read-only.
forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.cpp
86 lines (71 loc) · 1.53 KB
/
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
85
86
#include <iostream>
using namespace std;
void calculateLps(string pattern, int lps[])
{
int length = 0; // Length of the previous longest prefix suffix
unsigned int i;
lps[0] = 0;
i = 1;
// The loop calculates lps[i] for i = 1 to size - 1
while(i < pattern.size())
{
if(pattern[i] == pattern[length])
{
length++;
lps[i] = length;
i++;
}
else // If (pattern[i] != pattern[len])
{
if(length != 0)
length = lps[length - 1];
else
{
lps[i] = 0;
i++;
}
}
}
}
void KMPSearch(string pattern, string text)
{
int sizePattern = pattern.size();
int sizeText = text.size();
int *lps = new int[sizePattern];
int j = 0;
calculateLps(pattern, lps);
int i = 0;
while(i < sizeText)
{
if (pattern[j] == text[i])
{
j++;
i++;
}
if(j == sizePattern)
{
cout << "Pattern found at " << i - j + 1 << endl;
j = lps[j - 1];
}
else if (i < sizeText && pattern[j] != text[i])
{
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
delete[] lps;
}
int main()
{
string text = "namanchamanbomanamansanam";
string pattern = "aman";
KMPSearch(pattern, text);
return 0;
}
/* Output
Pattern found at 2
Pattern found at 8
Pattern found at 17
*/