Skip to content

Add KMP string matching algorithm (#2719) #2930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions strings/kmp_string_matching.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @file kmp_string_matching.cpp
* @brief Implementation of the Knuth-Morris-Pratt (KMP) string matching algorithm
*
* @details
* The KMP algorithm improves the naive string matching method by avoiding unnecessary rechecking of characters.
* It uses a precomputed Longest Prefix Suffix (LPS) array to efficiently search for a pattern in a given text.
*
* Time Complexity: O(n + m), where n = length of text, m = length of pattern.
* Space Complexity: O(m), for the LPS array.
*
* @author YashAstro11
* @date 2025-04-13
*/

#include <iostream>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
#include <iostream>
#include <iostream>![IMG_20250521_152127_815.jpg](https://github.com/user-attachments/assets/4efe756b-ed42-4c5c-9d8b-13b50339b786)
- # - [ ] []()_******_
```suggestion
#include <iostream>

******

#include <vector>
using namespace std;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

452546

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vector<int> computeLPS(const string& pattern) {
int n = pattern.length();
vector<int> lps(n, 0);
int len = 0;

for (int i = 1; i < n; ) {
if (pattern[i] == pattern[len]) {
lps[i++] = ++len;
} else if (len != 0) {
len = lps[len - 1];
} else {
lps[i++] = 0;
}
}
return lps;
}

void KMPSearch(const string& text, const string& pattern) {
vector<int> lps = computeLPS(pattern);
int i = 0, j = 0;
int n = text.length(), m = pattern.length();

while (i < n) {
if (pattern[j] == text[i]) {
i++, j++;
}

if (j == m) {
cout << "Pattern found at index " << i - j << endl;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

457

j = lps[j - 1];
} else if (i < n && pattern[j] != text[i]) {
j = (j != 0) ? lps[j - 1] : 0;
}
}
}

int main() {
string text = "ababcabcabababd";
string pattern = "ababd";
KMPSearch(text, pattern);
return 0;
}