Skip to content

Commit 0cfac90

Browse files
committed
String Matching Algo: KMP (knuth Morris Pratt) Algo'
1 parent f0bd36e commit 0cfac90

File tree

4 files changed

+62
-0
lines changed

4 files changed

+62
-0
lines changed
+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
5 3
2+
4 0 3 -12 1

Algorithms/String Matching/KMP/main.c

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <stdio.h>
2+
#include <string.h>
3+
4+
void computeLPS(char *P, int m, int *lps){
5+
// 0th index letter always set to 0
6+
lps[0] = 0;
7+
int k = 0;
8+
9+
for(int q = 1; q < m; q++){
10+
// Compare P with P until k > 0;
11+
while(k > 0 && P[q] != P[k]){
12+
k = lps[k-1];
13+
}
14+
15+
// If match
16+
if(P[q] == P[k]){
17+
// Increment k value
18+
k++;
19+
}
20+
21+
// Store in lps
22+
lps[q] = k;
23+
}
24+
}
25+
26+
int main(){
27+
char str[] = "ababcabcabababd";
28+
int n = strlen(str);
29+
30+
char P[] = "ababd";
31+
int m = strlen(P);
32+
33+
int lps[m];
34+
computeLPS(P, m, lps);
35+
36+
printf("LPS array:\n");
37+
for (int i = 0; i < m; i++) {
38+
printf("%d ", lps[i]);
39+
}
40+
41+
int q = 0;
42+
// Now apply KMP algo
43+
for (int i = 0; i < n; i++) {
44+
while (q > 0 && str[i] != P[q]) {
45+
q = lps[q - 1];
46+
}
47+
48+
if (str[i] == P[q]) {
49+
q++;
50+
}
51+
52+
if (q == m) {
53+
printf("Pattern found at index %d\n", i - m + 1);
54+
q = lps[q - 1]; // To continue searching for next occurrence
55+
}
56+
}
57+
58+
return 0;
59+
}
40.4 KB
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
0-12-12

0 commit comments

Comments
 (0)