Skip to content

Commit 543229b

Browse files
authored
Merge pull request #45 from nandikeshsingh/master
KMP-Algorithm
2 parents 9394535 + 43832d2 commit 543229b

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
//C++ code to find a pattern in a given text using KMP algorithm in linear time.
2+
#include<bits/stdc++.h>
3+
4+
using namespace std;
5+
6+
int main()
7+
{
8+
string text;
9+
string pattern;
10+
11+
cin>>text;//inputting text
12+
cout<<endl;
13+
14+
cin>>pattern;//inputting pattern
15+
cout<<endl;
16+
17+
int pattern_length=pattern.size();//variable to store length of pattern string
18+
int text_length=text.size();//variable to store length of text string
19+
20+
if(pattern_length>text_length)//if pattern_length is greater than text it is not possible to find pattern in text.
21+
{
22+
cout<<"Not Found"<<endl;
23+
exit(0);
24+
}
25+
26+
int temp[pattern_length];//i th element in the temp array will store the length of the longest suffix which is equal to the prefix in pattern array upto i th index.
27+
28+
int i=1,j=0;
29+
30+
/*Suppose the patteren is ababa then temp[4] would store value 3 as the length of longest prefix(aba) which is equal
31+
to the longest suffix(aba) is 3 upto 4 th index in the pattern.The entire temp array would look like 0 0 1 2 3.*/
32+
temp[0]=0;
33+
while(i<pattern_length)//Building the temp array.
34+
{
35+
if(pattern[i]==pattern[j])
36+
{
37+
temp[i]=j+1;
38+
i++;
39+
j++;
40+
}
41+
else if(pattern[i]!=pattern[j] && j==0)
42+
{
43+
temp[i]=0;
44+
i++;
45+
}
46+
else
47+
{
48+
j=temp[j-1];
49+
}
50+
}
51+
52+
i=0;
53+
j=0;
54+
/*Suppose our text is abacd and our pattern is abad.During our first mismatch that is at d(j=3)in pattern and c(i=3)in text,
55+
unlike the naive string search we won't start again from i=1 in text and j=0 in pattern instead we look in temp[2] which will
56+
have value 1 and we set j to 1 and we will again start doing search from i=3 and j=1.*/
57+
while(j<pattern_length && i<text_length) //implementing the KMP alogorithm
58+
{
59+
if(pattern[j]==text[i])
60+
{
61+
j++;
62+
i++;
63+
}
64+
else if(pattern[j]!=text[i] && j==0)
65+
{
66+
i++;
67+
}
68+
else
69+
{
70+
j=temp[j-1];
71+
}
72+
}
73+
74+
if(j==pattern_length)
75+
cout<<"Match Found and the starting index is "<<i-pattern_length<<endl;
76+
else
77+
cout<<"Not Found"<<endl;
78+
79+
return 0;
80+
}

0 commit comments

Comments
 (0)