有一种是直接将两个合并,getnext得到前后缀最长匹配字段即可,但是要注意长度小于两个字符串长度
另一种办法是得到一个字符模板串的next数组,然后 对另一字符串进行匹配,直至字符串末尾,若正在匹配中的模板串下标值不为0,说明可匹配,输出即可
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
const int N = 1e6+5;
int nxt[N];
int cnt = 0;
char s1[N], s2[N];
void GetNext(char s[], int length)
{
int i=0, j=-1;
nxt[0] = -1;//必须有...
while(i < length) {
if(j == -1 || s[i] == s[j]) {
i++;
j++;
nxt[i] = j;
}
else j = nxt[j];
}
}
void KMP(char s1[], int n, char s2[], int m)
{
int i = 0, j = 0;
while(i < n) {//一只匹配,直到最后
if(j == -1 || s1[i] == s2[j]) {
i++;
j++;
}
else
j = nxt[j];
}
if (j) {//说明匹配到最后有可以匹配的后缀
for (int k = 0; k < j; k++) cout << s2[k] ;
cout << " " << j << endl ;
}
else cout << 0 << endl ;
}
int main()
{
int T;
// cin >> T;
while(~scanf("%s%s", s1, s2)) {
cnt = 0;
int n, m;
n = strlen(s2);
m = strlen(s1);
GetNext(s1, m);
KMP(s2, n, s1, m);
}
return 0;
}