Skip to content

Commit 732e4b1

Browse files
Merge pull request #232 from harshendram/Algo/KMP
Added the implmentation of KMP algorithm in cpp
2 parents a8ff164 + a940d31 commit 732e4b1

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// Function to compute the LPS (Longest Prefix Suffix) array
5+
void computeLPSArray(const string &pattern, vector<int> &lps)
6+
{
7+
int m = pattern.size();
8+
int len = 0; // length of previous longest prefix suffix
9+
lps[0] = 0; // lps[0] is always 0
10+
11+
int i = 1;
12+
while (i < m)
13+
{
14+
if (pattern[i] == pattern[len])
15+
{
16+
len++;
17+
lps[i] = len;
18+
i++;
19+
}
20+
else
21+
{
22+
if (len != 0)
23+
{
24+
len = lps[len - 1];
25+
}
26+
else
27+
{
28+
lps[i] = 0;
29+
i++;
30+
}
31+
}
32+
}
33+
}
34+
35+
// KMP Search function
36+
void KMPSearch(const string &text, const string &pattern)
37+
{
38+
int n = text.size();
39+
int m = pattern.size();
40+
41+
vector<int> lps(m);
42+
computeLPSArray(pattern, lps);
43+
44+
int i = 0; // index for text
45+
int j = 0; // index for pattern
46+
while (i < n)
47+
{
48+
if (pattern[j] == text[i])
49+
{
50+
i++;
51+
j++;
52+
}
53+
54+
if (j == m)
55+
{
56+
cout << "Pattern found at index " << (i - j) << endl;
57+
j = lps[j - 1]; // Move pattern index based on lps
58+
}
59+
else if (i < n && pattern[j] != text[i])
60+
{
61+
if (j != 0)
62+
{
63+
j = lps[j - 1];
64+
}
65+
else
66+
{
67+
i++;
68+
}
69+
}
70+
}
71+
}
72+
73+
int main()
74+
{
75+
string text, pattern;
76+
77+
cout << "Enter the text: ";
78+
getline(cin, text);
79+
80+
cout << "Enter the pattern: ";
81+
getline(cin, pattern);
82+
83+
KMPSearch(text, pattern);
84+
85+
return 0;
86+
}

0 commit comments

Comments
 (0)