C Program for KMP Algorithm for Pattern Searching


In this problem, we are given two strings a text and a pattern. Our task is to create a program for KMP algorithm for pattern search, it will find all the occurrences of pattern in text string.

Here, we have to find all the occurrences of patterns in the text.

Let’s take an example to understand the problem,

Input

text = “xyztrwqxyzfg” pattern = “xyz”

Output

Found at index 0
Found at index 7

Here, we will discuss the solution to the problem using KMP (Knuth Morris Pratt) pattern searching algorithm, it will use a preprocessing string of the pattern which will be used for matching in the text. And help’s in processing or finding pattern matches in the case where matching characters are followed by the character of the string that does not match the pattern.

We will preprocess the pattern wand to create an array that contains the proper prefix and suffix from the pattern that will help in finding the mismatch patterns.

Program for KMP Algorithm for Pattern Searching

// C Program for KMP Algorithm for Pattern Searching

Example

 Live Demo

#include<iostream>
#include<string.h>
using namespace std;
void prefixSuffixArray(char* pat, int M, int* pps) {
   int length = 0;
   pps[0] = 0;
   int i = 1;
   while (i < M) {
      if (pat[i] == pat[length]) {
         length++;
         pps[i] = length;
         i++;
      } else {
         if (length != 0)
         length = pps[length - 1];
         else {
            pps[i] = 0;
            i++;
         }
      }
   }
}
void KMPAlgorithm(char* text, char* pattern) {
   int M = strlen(pattern);
   int N = strlen(text);
   int pps[M];
   prefixSuffixArray(pattern, M, pps);
   int i = 0;
   int j = 0;
   while (i < N) {
      if (pattern[j] == text[i]) {
         j++;
         i++;
      }
      if (j == M) {
         printf("Found pattern at index %d
", i - j);          j = pps[j - 1];       }       else if (i < N && pattern[j] != text[i]) {          if (j != 0)          j = pps[j - 1];          else          i = i + 1;       }    } } int main() {    char text[] = "xyztrwqxyzfg";    char pattern[] = "xyz";    printf("The pattern is found in the text at the following index :
");    KMPAlgorithm(text, pattern);    return 0; }

Output

The pattern is found in the text at the following index −

Found pattern at index 0
Found pattern at index 7

Updated on: 17-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements