#include<bits/stdc++.h>
using namespace std;
vector<int> arrayvalue(string ch)
{
int i, index, l = ch.size();
vector<int>lps(l);
index = 0;
for(i=1;i<l; )
{
if(ch[i] == ch[index])
{
lps[i] = index + 1;
i++;
index++;
}
else
{
if(index != 0)
index = lps[index - 1];
else
{
lps[i] = index;
i++;
}
}
}
return lps;
}
void kmp(string ch, string an)
{
int i, j, l = an.size();
bool ans = false;
vector<int>lps = arrayvalue(an);
i= j = 0;
while(i<ch.size())
{
if(ch[i] == an[j])
{
i++;
j++;
}
else
{
if(j != 0)
j = lps[j-1];
else
i++;
}
if(j == l)
{
cout << "Sub-String is Found." << endl;
ans = true;
break;
}
}
if(ans == false)
{
cout << "Sub-String is not Found." << endl;
}
}
int main()
{
string text, pattern;
cout << "Enter Main String :: ";
getline(cin, text);
cout << "Enter Sub-String :: ";
getline(cin, pattern);
cout << endl;
kmp(text, pattern);
return 0;
}
using namespace std;
vector<int> arrayvalue(string ch)
{
int i, index, l = ch.size();
vector<int>lps(l);
index = 0;
for(i=1;i<l; )
{
if(ch[i] == ch[index])
{
lps[i] = index + 1;
i++;
index++;
}
else
{
if(index != 0)
index = lps[index - 1];
else
{
lps[i] = index;
i++;
}
}
}
return lps;
}
void kmp(string ch, string an)
{
int i, j, l = an.size();
bool ans = false;
vector<int>lps = arrayvalue(an);
i= j = 0;
while(i<ch.size())
{
if(ch[i] == an[j])
{
i++;
j++;
}
else
{
if(j != 0)
j = lps[j-1];
else
i++;
}
if(j == l)
{
cout << "Sub-String is Found." << endl;
ans = true;
break;
}
}
if(ans == false)
{
cout << "Sub-String is not Found." << endl;
}
}
int main()
{
string text, pattern;
cout << "Enter Main String :: ";
getline(cin, text);
cout << "Enter Sub-String :: ";
getline(cin, pattern);
cout << endl;
kmp(text, pattern);
return 0;
}
Comments
Post a Comment