From 081ee1405e74bb560c0ed158fddb9e74631cb1e6 Mon Sep 17 00:00:00 2001 From: gitbeginner2020 <73686963+gitbeginner2020@users.noreply.github.com> Date: Fri, 30 Oct 2020 12:49:43 +0530 Subject: [PATCH] Create KMPAlgorithm.cpp --- Algorithm/KMPAlgorithm.cpp | 74 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Algorithm/KMPAlgorithm.cpp diff --git a/Algorithm/KMPAlgorithm.cpp b/Algorithm/KMPAlgorithm.cpp new file mode 100644 index 0000000..8e07b53 --- /dev/null +++ b/Algorithm/KMPAlgorithm.cpp @@ -0,0 +1,74 @@ +#include + +void computeLPSArray(char* pat, int M, int* lps); +void KMPSearch(char* pat, char* txt) +{ + int M = strlen(pat); + int N = strlen(txt); + + int lps[M]; + computeLPSArray(pat, M, lps); + + int i = 0; + int j = 0; + while (i < N) { + if (pat[j] == txt[i]) { + j++; + i++; + } + + if (j == M) { + printf("Found pattern at index %d ", i - j); + j = lps[j - 1]; + } + + + else if (i < N && pat[j] != txt[i]) { + + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } +} + + +void computeLPSArray(char* pat, int M, int* lps) +{ + + int len = 0; + + lps[0] = 0; // lps[0] is always 0 + + + int i = 1; + while (i < M) { + if (pat[i] == pat[len]) { + len++; + lps[i] = len; + i++; + } + else + { + + if (len != 0) { + len = lps[len - 1]; + + } + else + { + lps[i] = 0; + i++; + } + } + } +} + +int main() +{ + char txt[] = "ABABDABACDABABCABAB"; + char pat[] = "ABABCABAB"; + KMPSearch(pat, txt); + return 0; +}