-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathKMP Algorithm.c
91 lines (80 loc) · 1.9 KB
/
KMP Algorithm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <string.h>
void piTable(char pattern[], int pi[], int len)
{
int i = 0;
int j = 0;
i = 1;
j = 0;
pi[0] = 0;
//the loop will iterate the pattern and find the longest prefix and suffix at every index
while (i < len)
{
if (pattern[i] == pattern[j])
{
pi[i] = j + 1;
i++;
j++;
}
else if (j > 0)
{
j = pi[j - 1];
}
else
{
pi[i] = 0;
i++;
}
}
}
//kmp function to find if pattern exists or not
bool kmp(char text[], char pattern[])
{
//finding length of the text
int t_len = strlen(text);
//finding length of the pattern
int p_len = strlen(pattern);
//array in which we store the longest prefix and suffix at every index in pattern
int pi[p_len];
//calling function to calculate pi table for pattern
piTable(pattern, pi, p_len);
int i = 0;
int j = 0;
//this loop will iterate over text and find the pattern in it the pi table is used to eliminate duplicate comparisons
while (i < t_len)
{
if (text[i] == pattern[j])
{
i++;
j++;
}
else if (j > 0)
{
j = pi[j - 1];
}
else
{
j = 0;
i++;
}
//if j reaches the end of the pattern which means pattern exists in the text
if (j == p_len)
{
return true;
}
}
return false;
}
int main()
{
//text in which we have to search the pattern
char text[] = "aabacabadb";
//pattern we need to search
char pattern[] = "bacab";
//if we get true from kmp() then pattern found else pattern not found
if (kmp(text, pattern))
printf("Pattern Found in the Text!\n");
else
printf("Pattern does not found in Text!\n");
return 0;
}