BCS304 DS Module 1 KMP Algorithm
BCS304 DS Module 1 KMP Algorithm
#include <stdio.h>
#include <string.h>
while (i < M) {
if (pat[i] == pat[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
int lps[M];
computeLPSArray(pat, M, lps);
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
printf("Found pattern at index %d\n", i – j+1);
found = 1; // Pattern found
j = lps[j - 1];
} else if (i < N && pat[j] != txt[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
if (!found) {
printf("Pattern not found\n");
}
}
int main() {
char txt[100], pat[100];
printf("Enter the text: ");
gets(txt);
printf("Enter the pattern: ");
gets(pat);
KMPSearch(pat, txt);
return 0;
}
Output
Enter the text: ababcabcabababd
Enter the pattern: ababd
Found pattern at index 11