[go: up one dir, main page]

0% found this document useful (0 votes)
25 views2 pages

KMP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

KMP

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

//KMP

vector<int> buildLPSArray(string &pattern)


{
vector<int> lps;
lps.push_back(0);

int i = 1, len = 0;
while (i < pattern.length())
{
if (pattern[i] == pattern[len])
{
len++;
lps.push_back(len);
i++;
}
else
{
if (len == 0)
{
lps.push_back(0);
i++;
}
else
{
while (len > 0 || pattern[i] == pattern[len])
len = lps[len - 1];
}
}
}
return lps;
}

bool kmpMatching(string s, string pattern)


{
vector<int> lps = buildLPSArray(pattern);
// for (int i = 0; i < lps.size(); i++)
// cout << lps[i] << " ";
// cout << endl;

int j = -1, i = -1;


bool contains = false;
while (i < (int)s.length())
{
// cout << "i = " << i << ", j = " << j << endl;
if (s[i + 1] == pattern[j + 1])
{
j++;
i++;
}
else
{
if (j == -1)
{
i++;
}
else
j = lps[j] - 1;
}
if (j == (int)pattern.length() - 1)
{

// return true;
// contains = true;
j = lps[j] - 1;
cout << "Pattern found at index " << i - (int)pattern.length() + 1 <<
endl;
}
}

return contains;
}

int main()
{
string s, pattern;
getline(cin, s);
getline(cin, pattern);
bool a = kmpMatching(s, pattern);
// cout << (a ? "YES" : "NO") << endl;
// bool a = kmpMatching("asdiiababbcawiwabcndababbcadnabcdassabc", "ababbca");
// cout << a << endl;
// return 0;
}

You might also like