HDU 2594(求最长公共前后缀 kmp)

题意是在所给的两个字符串中找最长的公共前后缀,即第一个字符串前缀和第二个字符串后缀的最长相等串。

思路是将两个字符串拼接在一起,然后直接套用 kmp 算法即可。

要注意用 next 会报编译错误,改成 Next 才过……但 next 确实不是 c++ 关键字。

代码如下:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 const int N=50000+5;
 6 char a[N*2],b[N];
 7 int Next[N*2];
 8 void getNext()
 9 {
10     Next[0] = -1;
11     int i=1,j=0,len=strlen(a);
12     while(i<len)
13     {
14         if(j==-1||a[i]==a[j])
15         {
16             i++;j++;
17             Next[i]=j;
18         }
19         else
20             j=Next[j];
21     }
22 }
23 int main()
24 {
25     while(~scanf("%s%s",a,b))
26     {
27         int lena=strlen(a),lenb=strlen(b);
28         strcat(a,b);//将b字符串连在a字符串后
29         getNext();//求解Next数组
30         int ans=Next[strlen(a)];
31         while(ans>lenb||ans>lena) ans=Next[ans];
32         if(ans==0) puts("0");
33         else
34         {
35             a[ans] = 0;
36             printf("%s %d
",a,ans);
37         }
38     }
39     return 0;
40 }
View Code
原文地址:https://www.cnblogs.com/Taskr212/p/10047361.html