【题目来源】:https://vjudge.net/problem/HDU-2594
【题意】
求第一个字符串的前缀和第二个字符串的后缀的字符最大匹配量。
如:
riemann
marjorie
得:rie 字符数量是3、
【思路】
起初以为这道题依旧是有关于next数组的题,然后就有了一系列的代码应运而生。自己试的样例都过了,wrong的一塌糊涂。
额,初学者的我只知道kmp可以求一个字符串是否在另一个字符串里出现过,或者最多出现几次,并不知道里面怎么运行的,昨天没怎么思考,就过去了,今天就用跟踪的方法记录了一下j的数值,模拟运行了下。终于发现了奥妙。
简单来说,kmp就是一个不断匹配的过程,但是当第一个字符串(就是要求next数组的)长度小于第二个字符串时,会出现匹配突然断了的情况,这个时候的,就要j=next[j],重新找到最近的点继续匹配,一直匹配到最后,既然要匹配到最后,那么肯定能够知道前缀和后缀的最大匹配,也就是最后的j值。
【代码】
#include<set>
#include<map>
#include<stack>
#include<cmath>
#include<queue>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<limits.h>
#include<algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int mod=1e9+7;
const double esp=1e-5;
typedef unsigned long long ll;
typedef long long LL;
char s[50000+10],t[50000+10];
int nexx[50000+10];
int lens,lent;
void get_next()
{
int i=0,j;
j=nexx[0]=-1;
while(i<lens)
{
while(-1!=j&&s[i]!=s[j]) j=nexx[j];
nexx[++i]=++j;
}
}
int kmp()
{
int i=0,j=0;
get_next();
while(i<lent)
{
while(-1!=j&&t[i]!=s[j])
j=nexx[j];
++i; ++j;
if(j>lens)
j=nexx[j];
}
return j;
}
int main()
{
while(~scanf("%s",s))
{
scanf("%s",t);
lens=strlen(s);
lent=strlen(t);
int res=kmp();
if(s[0]=='\0'&&t[0]=='\0')
{
printf("0\n");
continue;
}
if(res)
{
s[res]='\0';
printf("%s %d\n",s,res);
}
else
printf("0\n");
}
}