
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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