-
Notifications
You must be signed in to change notification settings - Fork 1
/
KMP_GENERAL.cpp
66 lines (63 loc) · 959 Bytes
/
KMP_GENERAL.cpp
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
#include<bits/stdc++.h>
using namespace std;
int Search_Pattern(string s,string p,vector<int> F)
{
int i,j;
i=0;
j=-1;
while(j+1!=p.length() && i<s.length())
{
if(s[i]==p[j+1])
{
i++;
j++;
}
else
{
if(j==-1)
i++;
else
j=F[j]-1;
}
}
if(j+1==p.length())
return (i-p.length());
else
return -1;
}
vector<int> CreatePrefix(string s)
{
int n = (int) s.length() ;
vector<int> F(n);
F[0]=0;
for(int i=1;i<n;i++)
{
int j = F[i-1];
while(j>0 && s[i]!=s[j])
j=F[j-1];
if(s[i]==s[j])
j++;
F[i]=j;
}
return F;
}
int main()
{
string s,p;
vector<int> v;
cout<<"Enter Major String : ";
cin>>s;
cout<<"Enter The Pattern : ";
cin>>p;
v=CreatePrefix(p);
int res=Search_Pattern(s,p,v);
if(res!=-1)
{
cout<<"Matched at index "<<res<<endl;
for(int i=res;i<res+p.length();i++)
cout<<s[i];
cout<<endl;
}
else
cout<<"Not Matched\n";
}