#include <stdio.h>
#include <string.h>
void Next(char*T, int *next) {
int i = 1;
next[1] = 0;
int j = 0;
while (i < strlen(T)) {
if (j == 0 || T[i - 1] == T[j - 1]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int KMP(char * S, char * T) {
/** 实现KMP算法, 若匹配返回匹配位置,若不匹配返回 -1 **/
/*************** begin *******************/
int i = 0, j = 0 ;
int next[1000];
Next(T,next);
//i代表主串当前待比较的位置,j代表子串当前待比较的位置
while(i<strlen(S) && j<strlen(T))
{
if(S[i] == T[j])
{
i++; //若当前字符相同,则继续向下比较
j++;
}
else //主串,子串指针回溯重新开始下一次匹配
{
// i=i-j+1; //主串退回到开始匹配
// j=0; //子串从头开始匹配
j=next[j];
}
}
if(j>=strlen(T) )
return (i-strlen(T)+1 ); //返回匹配的第一个字符的下标
else
return -1; // 模式匹配不成功
/*************** end *********************/
}
int main() {
char a[1000], b[100];
scanf("%s %s", a, b);
int i = KMP(a, b);
printf("%d", i);
return 0;
}