Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views2 pages

KMP Pattern Matching in C

The document contains a C program that implements the Knuth-Morris-Pratt (KMP) pattern matching algorithm. It defines functions to compute the longest prefix suffix (LPS) array and to search for a pattern within a given text. The program outputs the position of the pattern if found, or indicates that the pattern is not present in the text.

Uploaded by

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

KMP Pattern Matching in C

The document contains a C program that implements the Knuth-Morris-Pratt (KMP) pattern matching algorithm. It defines functions to compute the longest prefix suffix (LPS) array and to search for a pattern within a given text. The program outputs the position of the pattern if found, or indicates that the pattern is not present in the text.

Uploaded by

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

C program to Implement a Pattern matching algorithms using Knuth-Morris-Pratt

Knuth-Morris-Pratt Pattern matching


#include <stdio.h>
#include <string.h>

int lps[100];
void longestPrefixSuffix(char p[])
{
int i=1,j=0;
int m = strlen(p);
lps[0] = 0;
while(i < m)
{
if( p[j] == p[i])
{
lps[i]=j+1;
i++;
j++;
}
else if(j>0)
j = lps[j-1];
else
{
lps[i]=0;
i++;
}
}
}

int kmp (char p[],char t[])


{
int n,m;
int i=0,j=0;
n = strlen(t);
m = strlen(p);
longestPrefixSuffix(p);
while( i < n )
{
if ( p[j] == t[i])
{
if (j == m-1 )
return i-j;
i++;
j++;
}
else if(j>0)
j = lps[j-1];
else
i++;
}
return 0;
}

int main() {
char t[]="kiss*miss*in*mississippi";
char p[]="missi";
int i;
i=kmp(p,t);
if(i)
printf("pattern is present in text at position %d",i+1);
else
printf("pattern is not present in text");
return 0;
}

OUTPUT
pattern is present in text at position 14

You might also like