大致思路:
很明显的“首尾比较”的题,就是拓展KMP的模板题了。
这里把getnext()和getextend()套上去,注意输入从1开始。模板题解决。
AC代码:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
char t[50010],s[50010]; //t是匹配前面的,s是匹配后面的
int n,m; //n是t的长度,m是s的长度
int nextt[50010];
int extend[50010];
void getnext() {
nextt[1] = n;
int p = 1;
while(p < n && t[p] == t[p + 1]) p++;
nextt[2] = p-1;
int k = 2,l;
for(int i = 3; i <= n; i++) {
p = k + nextt[k] - 1;
l = nextt[i - k + 1];
if (i + l <= p) nextt[i] = l;
else {
int j = p - i + 1;
if(j < 0) j = 0;
while(i + j <= n && t[i + j] == t[j + 1]) j++;
nextt[i] = j;
k = i;
}
}
}
void getextend() {
int p = 0;
while (p < m && p < n && s[p + 1] == t[p + 1]) {
p++;
}
extend[1] = p;
int k = 1, l;
for (int i = 2; i <= m; i++) {
p = k + extend[k] - 1;
l = nextt[i - k + 1];
if (i + l <= p) {
extend[i] = l;
} else {
int j = p - i + 1;
if(j < 0) j = 0;
while(i + j <= m && j + 1 <=n && s[i + j] == t[j + 1]) j ++;
extend[i] = j;
k = i;
}
}
}
int main()
{
gets(t+1);
gets(s+1);
n=strlen(t+1);
m=strlen(s+1);
getnext();
getextend();
int maxx=0;
for(int i=1;i<=m;i++)
{
maxx=max(maxx,extend[i]);
}
if(maxx!=0)
{
for(int i=1;i<=maxx;i++)
cout<<t[i];
cout<<" ";
}
cout<<maxx;
return 0;
}