Skip to content

Commit e777b32

Browse files
author
Yash Yadav
committed
Add KMP string matching algorithm (TheAlgorithms#2719)
1 parent 77b9f39 commit e777b32

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

strings/kmp_string_matching.cpp

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* @file kmp_string_matching.cpp
3+
* @brief Implementation of the Knuth-Morris-Pratt (KMP) string matching algorithm
4+
*
5+
* @details
6+
* The KMP algorithm improves the naive string matching method by avoiding unnecessary rechecking of characters.
7+
* It uses a precomputed Longest Prefix Suffix (LPS) array to efficiently search for a pattern in a given text.
8+
*
9+
* Time Complexity: O(n + m), where n = length of text, m = length of pattern.
10+
* Space Complexity: O(m), for the LPS array.
11+
*
12+
* @author YashAstro11
13+
* @date 2025-04-13
14+
*/
15+
16+
#include <iostream>
17+
#include <vector>
18+
using namespace std;
19+
20+
vector<int> computeLPS(const string& pattern) {
21+
int n = pattern.length();
22+
vector<int> lps(n, 0);
23+
int len = 0;
24+
25+
for (int i = 1; i < n; ) {
26+
if (pattern[i] == pattern[len]) {
27+
lps[i++] = ++len;
28+
} else if (len != 0) {
29+
len = lps[len - 1];
30+
} else {
31+
lps[i++] = 0;
32+
}
33+
}
34+
return lps;
35+
}
36+
37+
void KMPSearch(const string& text, const string& pattern) {
38+
vector<int> lps = computeLPS(pattern);
39+
int i = 0, j = 0;
40+
int n = text.length(), m = pattern.length();
41+
42+
while (i < n) {
43+
if (pattern[j] == text[i]) {
44+
i++, j++;
45+
}
46+
47+
if (j == m) {
48+
cout << "Pattern found at index " << i - j << endl;
49+
j = lps[j - 1];
50+
} else if (i < n && pattern[j] != text[i]) {
51+
j = (j != 0) ? lps[j - 1] : 0;
52+
}
53+
}
54+
}
55+
56+
int main() {
57+
string text = "ababcabcabababd";
58+
string pattern = "ababd";
59+
KMPSearch(text, pattern);
60+
return 0;
61+
}

0 commit comments

Comments
 (0)