#include <iostream>
using namespace std;
void computeLPSArray(char *pat, int M, int *lps)
{
int len = 0; // lenght of the previous longest prefix suffix
int i;
lps[0] = 0; // lps[0] is always 0
i = 1;
// the loop calculates lps[i] for i = 1 to M-1
while(i < M)
{
if(pat[i] == pat[len])
{
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if( len != 0 )
{
// This is tricky. Consider the example AAACAAAA and i = 7.
len = lps[len-1];
// Also, note that we do not increment i here
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}
void computeLPSArray2(char *pat, int M, int *lps)
{
int len = 0; // lenght of the previous longest prefix suffix
int i;
lps[0] = 0; // lps[0] is always 0
i = 1;
// the loop calculates lps[i] for i = 1 to M-1
while(i < M)
{
if(pat[i] == pat[len])
{
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if( len != 0 )
{
// This is tricky. Consider the example AAACAAAA and i = 7.
len = len-1;
// Also, note that we do not increment i here
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}
int main() {
char pat[]="aabcbabc";
int *lps=new int[7];
computeLPSArray(pat,7,lps);
for(int i=0;i<7;++i)
cout<<pat[i]<<" ";
cout<<endl;
for(int i=0;i<7;++i)
cout<<lps[i]<<" ";
computeLPSArray2(pat,7,lps);
cout<<endl;
for(int i=0;i<7;++i)
cout<<lps[i]<<" ";
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwp2b2lkIGNvbXB1dGVMUFNBcnJheShjaGFyICpwYXQsIGludCBNLCBpbnQgKmxwcykKewogICAgaW50IGxlbiA9IDA7ICAvLyBsZW5naHQgb2YgdGhlIHByZXZpb3VzIGxvbmdlc3QgcHJlZml4IHN1ZmZpeAogICAgaW50IGk7CiAKICAgIGxwc1swXSA9IDA7IC8vIGxwc1swXSBpcyBhbHdheXMgMAogICAgaSA9IDE7CiAKICAgIC8vIHRoZSBsb29wIGNhbGN1bGF0ZXMgbHBzW2ldIGZvciBpID0gMSB0byBNLTEKICAgIHdoaWxlKGkgPCBNKQogICAgewogICAgICAgaWYocGF0W2ldID09IHBhdFtsZW5dKQogICAgICAgewogICAgICAgICBsZW4rKzsKICAgICAgICAgbHBzW2ldID0gbGVuOwogICAgICAgICBpKys7CiAgICAgICB9CiAgICAgICBlbHNlIC8vIChwYXRbaV0gIT0gcGF0W2xlbl0pCiAgICAgICB7CiAgICAgICAgIGlmKCBsZW4gIT0gMCApCiAgICAgICAgIHsKICAgICAgICAgICAvLyBUaGlzIGlzIHRyaWNreS4gQ29uc2lkZXIgdGhlIGV4YW1wbGUgQUFBQ0FBQUEgYW5kIGkgPSA3LgogICAgICAgICAgIGxlbiA9IGxwc1tsZW4tMV07CiAKICAgICAgICAgICAvLyBBbHNvLCBub3RlIHRoYXQgd2UgZG8gbm90IGluY3JlbWVudCBpIGhlcmUKICAgICAgICAgfQogICAgICAgICBlbHNlIC8vIGlmIChsZW4gPT0gMCkKICAgICAgICAgewogICAgICAgICAgIGxwc1tpXSA9IDA7CiAgICAgICAgICAgaSsrOwogICAgICAgICB9CiAgICAgICB9CiAgICB9Cn0Kdm9pZCBjb21wdXRlTFBTQXJyYXkyKGNoYXIgKnBhdCwgaW50IE0sIGludCAqbHBzKQp7CiAgICBpbnQgbGVuID0gMDsgIC8vIGxlbmdodCBvZiB0aGUgcHJldmlvdXMgbG9uZ2VzdCBwcmVmaXggc3VmZml4CiAgICBpbnQgaTsKIAogICAgbHBzWzBdID0gMDsgLy8gbHBzWzBdIGlzIGFsd2F5cyAwCiAgICBpID0gMTsKIAogICAgLy8gdGhlIGxvb3AgY2FsY3VsYXRlcyBscHNbaV0gZm9yIGkgPSAxIHRvIE0tMQogICAgd2hpbGUoaSA8IE0pCiAgICB7CiAgICAgICBpZihwYXRbaV0gPT0gcGF0W2xlbl0pCiAgICAgICB7CiAgICAgICAgIGxlbisrOwogICAgICAgICBscHNbaV0gPSBsZW47CiAgICAgICAgIGkrKzsKICAgICAgIH0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