題意:
給定兩個字符串p和s,求字符串p的前綴和字符串s的後綴能匹配的最大長度,並輸出匹配的子串
思路:
把s連接在p的後面,對新的字符串p求next數組,
#include <cstdio>
#include <cstring>
const int maxn = 100005;
char p[maxn];
int len,next[maxn];
void getnext(char* p)
{
next[1] = 0;
int k = 0;
for(int i=2;i<=len;i++)
{
while(k!=0 && p[k+1]!=p[i]) k = next[k];
if(p[k+1] == p[i]) k++;
next[i] = k;
}
}
int main()
{
while(scanf("%s",p+1)!=EOF)
{
len = strlen(p+1);
p[++len] = '$';
scanf("%s",p+len+1);
len+= strlen(p+len+1);
getnext(p);
for(int i=1;i<=next[len];i++)
{
printf("%c",p[i]);
}
if(next[len]) printf(" ");
printf("%d\n",next[len]);
}
return 0;
}