This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/*
* C++ Program to Implement Knuth–Morris–Pratt Algorithm (KMP)
*/
#include<iostream>
#include<cstring>
usingnamespacestd;
voidpreKMP(stringpattern,intf[])
{
intm=pattern.length(),k;
f[0]=-1;
for(inti=1;i<m;i++)
{
k=f[i-1];
while(k>=0)
{
if(pattern[k]==pattern[i-1])
break;
else
k=f[k];
}
f[i]=k+1;
}
}
//check whether target string contains pattern
boolKMP(stringpattern,stringtarget)
{
intm=pattern.length();
intn=target.length();
intf[m];
preKMP(pattern,f);
inti=0;
intk=0;
while(i<n)
{
if(k==-1)
{
i++;
k=0;
}
elseif(target[i]==pattern[k])
{
i++;
k++;
if(k==m)
return1;
}
else
k=f[k];
}
return0;
}
intmain()
{
stringtar="san and linux training";
stringpat="lin";
if(KMP(pat,tar))
cout<<"'"<<pat<<"' found in string '"<<tar<<"'"<<endl;
else
cout<<"'"<<pat<<"' not found in string '"<<tar<<"'"<<endl;
pat="sanfoundry";
if(KMP(pat,tar))
cout<<"'"<<pat<<"' found in string '"<<tar<<"'"<<endl;
else
cout<<"'"<<pat<<"' not found in string '"<<tar<<"'"<<endl;
return0;
}
/*
'lin' found in string 'san and linux training'
'sanfoundry' not found in string 'san and linux training'