Skip to content
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

Add KMP Search Algorithm #2821

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
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
58 changes: 58 additions & 0 deletions search/KMPAlgorithm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#include <iostream>
dev-priyanshu15 marked this conversation as resolved.
Show resolved Hide resolved
#include <vector>
#include <string>

std::vector<int> computeLPSArray(const std::string& pattern) {
int m = pattern.size();
std::vector<int> lps(m);
int len = 0;
int i = 1;

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

void KMP(const std::string& text, const std::string& pattern) {
int n = text.size();
int m = pattern.size();
std::vector<int> lps = computeLPSArray(pattern);
int i = 0, j = 0;

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

if (j == m) {
std::cout << "Pattern found at index " << i - j << std::endl;
j = lps[j - 1];
} else if (i < n && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
}

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