推理过程见详解 .
#include <bits/stdc++.h>
#define LL long long
#define Pi acos(-1.0)
#define INF 2147483646
#define eps 1e-9
#define MS 100009
#define mss 17
using namespace std;
// Notice the data size
int n,m,k;
int p[MS],nex[MS];
char s[MS],ts[MS];
void get_next(char ts[],int len){
int j=0,k=-1;
nex[0] = -1;
while(j<len-1){
if(k==-1||ts[j] == ts[k]){
// 当 ts[j+1] == ts[nex[j+1]] 时要跳过
if(ts[++j] == ts[++k])
nex[j] = nex[k];
else
nex[j] = k;
}
else k = nex[k];
}
}
int kmp(char s[],char ts[],int h1,int h2){
int i,j;
i = j = 0;
while(i<h1 && j<h2){
if(s[i] == ts[j] || j == -1){
i++ ,j++;
}
else j = nex[j];
}
if(j == h2) return i-j; // 返回从 0 开始的主串下标
else return -1;
}
int main() {
cin >> s;
cin >> ts;
get_next(ts,strlen(ts));
int ans = kmp(s,ts,strlen(s),strlen(ts));
printf("%d\n",ans);
return 0;
}
/*
input : 0123456789
567
output: 5
*/