Skip to content

Commit d80db41

Browse files
authoredOct 2, 2022
KMP Algorithm for pattern searching
1 parent 6ca5b06 commit d80db41

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
 

‎KMP Algorithm for pattern Searching

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include <bits/stdc++.h>
2+
3+
void computeLPSArray(char* pat, int M, int* lps);
4+
5+
// Prints occurrences of txt[] in pat[]
6+
void KMPSearch(char* pat, char* txt)
7+
{
8+
int M = strlen(pat);
9+
int N = strlen(txt);
10+
11+
// create lps[] that will hold the longest prefix suffix
12+
// values for pattern
13+
int lps[M];
14+
15+
// Preprocess the pattern (calculate lps[] array)
16+
computeLPSArray(pat, M, lps);
17+
18+
int i = 0; // index for txt[]
19+
int j = 0; // index for pat[]
20+
while ((N - i) >= (M - j)) {
21+
if (pat[j] == txt[i]) {
22+
j++;
23+
i++;
24+
}
25+
26+
if (j == M) {
27+
printf("Found pattern at index %d ", i - j);
28+
j = lps[j - 1];
29+
}
30+
31+
// mismatch after j matches
32+
else if (i < N && pat[j] != txt[i]) {
33+
// Do not match lps[0..lps[j-1]] characters,
34+
// they will match anyway
35+
if (j != 0)
36+
j = lps[j - 1];
37+
else
38+
i = i + 1;
39+
}
40+
}
41+
}
42+
43+
// Fills lps[] for given pattern pat[0..M-1]
44+
void computeLPSArray(char* pat, int M, int* lps)
45+
{
46+
// length of the previous longest prefix suffix
47+
int len = 0;
48+
49+
lps[0] = 0; // lps[0] is always 0
50+
51+
// the loop calculates lps[i] for i = 1 to M-1
52+
int i = 1;
53+
while (i < M) {
54+
if (pat[i] == pat[len]) {
55+
len++;
56+
lps[i] = len;
57+
i++;
58+
}
59+
else // (pat[i] != pat[len])
60+
{
61+
// This is tricky. Consider the example.
62+
// AAACAAAA and i = 7. The idea is similar
63+
// to search step.
64+
if (len != 0) {
65+
len = lps[len - 1];
66+
67+
// Also, note that we do not increment
68+
// i here
69+
}
70+
else // if (len == 0)
71+
{
72+
lps[i] = 0;
73+
i++;
74+
}
75+
}
76+
}
77+
}
78+
79+
// Driver program to test above function
80+
int main()
81+
{
82+
char txt[] = "ABABDABACDABABCABAB";
83+
char pat[] = "ABABCABAB";
84+
KMPSearch(pat, txt);
85+
return 0;
86+
}

0 commit comments

Comments
 (0)
Please sign in to comment.