0% found this document useful (0 votes)
8 views3 pages

9912 KMPAlgo

The document contains a C program that implements the Knuth-Morris-Pratt (KMP) string matching algorithm. It includes functions to compute the Longest Prefix Suffix (LPS) array and to search for a given pattern within a text. The main function demonstrates the KMP search by looking for a specific pattern in a sample text.

Uploaded by

neillobo360
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

9912 KMPAlgo

The document contains a C program that implements the Knuth-Morris-Pratt (KMP) string matching algorithm. It includes functions to compute the Longest Prefix Suffix (LPS) array and to search for a given pattern within a text. The main function demonstrates the KMP search by looking for a specific pattern in a sample text.

Uploaded by

neillobo360
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <stdio.

h>

#include <string.h>

void computeLPSArray(char* pattern, int M, int* lps) {

int len = 0;

lps[0] = 0;

int i = 1;

while (i < M) {

if (pattern[i] == pattern[len]) {

len++;

lps[i] = len;

i++;

} else {

if (len != 0) {

len = lps[len - 1];

} else {

lps[i] = 0;

i++;

void KMPSearch(char* pattern, char* text) {


int M = strlen(pattern);

int N = strlen(text);

int lps[M];

computeLPSArray(pattern, M, lps);

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\n", i - j);

j = lps[j - 1];

} else if (i < N && pattern[j] != text[i]) {

if (j != 0)

j = lps[j - 1];

else

i++;

int main() {
char text[] = "ABABDABACDABABCABAB";

char pattern[] = "ABABCABAB";

KMPSearch(pattern, text);

return 0;

Output:

You might also like