From c3335666d0e55d7049d5cf6575ea7093c49845d0 Mon Sep 17 00:00:00 2001 From: Tapesh Dua <71540051+Tapesh-1308@users.noreply.github.com> Date: Sat, 8 Oct 2022 11:35:28 +0530 Subject: [PATCH] Create KMP-algorithm.cpp --- .../CPlusPlus/Strings/KMP-algorithm.cpp | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 algorithms/CPlusPlus/Strings/KMP-algorithm.cpp diff --git a/algorithms/CPlusPlus/Strings/KMP-algorithm.cpp b/algorithms/CPlusPlus/Strings/KMP-algorithm.cpp new file mode 100644 index 00000000..efecd381 --- /dev/null +++ b/algorithms/CPlusPlus/Strings/KMP-algorithm.cpp @@ -0,0 +1,87 @@ +/* +* the Knuth–Morris–Pratt string-searching algorithm (or KMP algorithm) searches for +* occurrences of a "word" W within a main "text string" S by employing the observation +* that when a mismatch occurs, the word itself embodies sufficient information to +* determine where the next match could begin, thus bypassing re-examination of previously +* matched characters.(https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) +* Complexity of KMP algorithm +* Time complexity - O(n + m) +*/ + +#include +using namespace std; + +// Fills lps[] for given pattern pat[0..M-1] +void computeLPSArray(string &pat, int M, vector &lps) +{ + // length of the previous longest prefix suffix + int len = 0; + + // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + int i = 1; + while (i < M) { + if (pat[i] == pat[len]) { + len++; + lps[i] = len; + i++; + } + else // (pat[i] != pat[len]) + { + if (len != 0) + len = lps[len - 1]; + // Note that we do not increment i here + + else { // if (len == 0) + lps[i] = 0; + i++; + } + } + } +} + + +// Prints occurrences of txt[] in pat[] +void KMPSearch(string &pat, string &txt) +{ + int M = pat.length(); + int N = txt.length(); + + // create lps[] that will hold the longest prefix suffix values for pattern + vector lps(M, 0); + + // Preprocess the pattern (calculate lps array) + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt + int j = 0; // index for pat + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } + + if (j == M) { + cout<<"Found pattern at index "<