kmp的变形,kmp算法是先将某穿和自身匹配,写出fail数组。我们只需要这个fail数组,它的最后一位存储了我们所要求的答案中的最大长度。然后每次利用fail数组向前跳转就可以得到所有答案。
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include
<
iostream
>
#include < cstdio >
#include < cstdlib >
#include < cstring >
#include < stack >
using namespace std;
#define maxn 400005
char s[maxn];
int fail[maxn];
void kmp( char * pat)
{
int i, k;
memset(fail, - 1 , sizeof (fail));
for (i = 1 ; pat[i]; ++ i)
{
for (k = fail[i - 1 ]; k >= 0 && pat[i] != pat[k + 1 ];
k = fail[k]);
if (pat[k + 1 ] == pat[i]) fail[i] = k + 1 ;
}
}
int main()
{
// freopen("D:\\t.txt", "r", stdin);
while (scanf( " %s " , s) != EOF)
{
kmp(s);
int temp = strlen(s) - 1 ;
stack < int > stk;
while (temp != - 1 )
{
stk.push(temp + 1 );
temp = fail[temp];
}
printf( " %d " , stk.top());
stk.pop();
while ( ! stk.empty())
{
printf( " %d " , stk.top());
stk.pop();
}
printf( " \n " );
}
return 0 ;
}
#include < cstdio >
#include < cstdlib >
#include < cstring >
#include < stack >
using namespace std;
#define maxn 400005
char s[maxn];
int fail[maxn];
void kmp( char * pat)
{
int i, k;
memset(fail, - 1 , sizeof (fail));
for (i = 1 ; pat[i]; ++ i)
{
for (k = fail[i - 1 ]; k >= 0 && pat[i] != pat[k + 1 ];
k = fail[k]);
if (pat[k + 1 ] == pat[i]) fail[i] = k + 1 ;
}
}
int main()
{
// freopen("D:\\t.txt", "r", stdin);
while (scanf( " %s " , s) != EOF)
{
kmp(s);
int temp = strlen(s) - 1 ;
stack < int > stk;
while (temp != - 1 )
{
stk.push(temp + 1 );
temp = fail[temp];
}
printf( " %d " , stk.top());
stk.pop();
while ( ! stk.empty())
{
printf( " %d " , stk.top());
stk.pop();
}
printf( " \n " );
}
return 0 ;
}