/* Write a C program to implement the Knuth-Morris-Pratt (KMP) string matching
algorithm. The program should include:
� A function to preprocess the pattern and create the match table. � A function to search for all occurrences of the pattern in a given text using the KMP algorithm. */
#include <stdio.h> #include <string.h>
// Function to preprocess the pattern and create the LPS array
void computeLPSArray(char *pattern, int patternLength, int *lps) { int length = 0; // Length of the previous longest prefix suffix lps[0] = 0; // LPS[0] is always 0 int i = 1; // The loop calculates lps[i] for i = 1 to patternLength - 1 while (i < patternLength) { if (pattern[i] == pattern[length]) { length++; lps[i] = length; i++; } else { if (length != 0) { length = lps[length - 1]; // Note that we do not increment i here } else { lps[i] = 0; i++; } } } }
// Function to perform KMP string matching algorithm
void KMP_Search(char *text, char *pattern) { int textLength = strlen(text); int patternLength = strlen(pattern); int lps[patternLength]; // Create lps array // Preprocess the pattern to create the LPS array computeLPSArray(pattern, patternLength, lps); int i = 0; // Index for text int j = 0; // Index for pattern while (i < textLength) { if (pattern[j] == text[i]) { i++; j++; } if (j == patternLength) { printf("Pattern found at index %d\n", i - j); j = lps[j - 1]; // Reset j using the LPS array } else if (i < textLength && pattern[j] != text[i]) { // Mismatch after j matches if (j != 0) { j = lps[j - 1]; // Use LPS to avoid unnecessary comparisons } else . { i++; } } } }
// Main function int main() { char text[1000]; char pattern[100];