knuth 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[i] == p[j])
        {
            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 = strlen(t), m = strlen(p);
    longestPrefixSuffix(p);
    int i = 0, j = 0;
    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 -1;
}
int main()
{
    char text[200], pattern[100];
    printf("Enter the text: ");
    fgets(text, sizeof(text), stdin);
    text[strcspn(text, "\n")] = 0;
    printf("Enter the pattern: ");
    fgets(pattern, sizeof(pattern), stdin);
    pattern[strcspn(pattern, "\n")] = 0;
    int pos = kmp(pattern, text);
    if (pos != -1)
        printf("Pattern found at position %d\n", pos);
    else
        printf("Pattern not found\n");
}


Comments

Popular posts from this blog

SINGLE LINKED LIST by smd

BANKING SYSYTEM DATABASE WITH RECORDS

CLL by smd