Skip to content

Commit 498187e

Browse files
Merge pull request #2 from dev-priyanshu15/dev-priyanshu15-patch-2
Create Knuth-Morris-Pratt (KMP) Algorithm for Pattern Searching
2 parents 0a59bd4 + 598a6e4 commit 498187e

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
vector<int> computeLPSArray(string& pattern) {
5+
int m = pattern.size();
6+
vector<int> lps(m);
7+
int len = 0;
8+
int i = 1;
9+
10+
while (i < m) {
11+
if (pattern[i] == pattern[len]) {
12+
len++;
13+
lps[i] = len;
14+
i++;
15+
} else {
16+
if (len != 0) {
17+
len = lps[len - 1];
18+
} else {
19+
lps[i] = 0;
20+
i++;
21+
}
22+
}
23+
}
24+
return lps;
25+
}
26+
27+
void KMP(string& text, string& pattern) {
28+
int n = text.size();
29+
int m = pattern.size();
30+
vector<int> lps = computeLPSArray(pattern);
31+
int i = 0, j = 0;
32+
33+
while (i < n) {
34+
if (pattern[j] == text[i]) {
35+
i++;
36+
j++;
37+
}
38+
39+
if (j == m) {
40+
cout << "Pattern found at index " << i - j << endl;
41+
j = lps[j - 1];
42+
} else if (i < n && pattern[j] != text[i]) {
43+
if (j != 0) {
44+
j = lps[j - 1];
45+
} else {
46+
i++;
47+
}
48+
}
49+
}
50+
}
51+
52+
int main() {
53+
string text = "ababcabcabababd";
54+
string pattern = "ababd";
55+
KMP(text, pattern);
56+
return 0;
57+
}

0 commit comments

Comments
 (0)