( 字符串专题 )【 KMP 】
给定两个字符串 s 和 t ,判断 t 是否为 s 的子串。
#include <stdio.h>
#include <string.h>
char s[1000005], t[1000005];
int prefix[1000005];
void getpre()
{
int now=-1;
int i=0,j;
int len = strlen(t);
prefix[0] = -1;
while ( i<len-1 ) {
if ( now==-1 || t[i]==t[now] ) {
now ++; i++;
prefix[i] = now;
}
else {
now = prefix[now];
}
}
}
void kmp()
{
int i=0,j=0;
int lens = strlen(s);
int lent = strlen(t);
while ( i<lens && j<lent ) {
if ( j==-1 || s[i]==t[j] ) {
i ++; j ++;
}
else {
j = prefix[j];
}
}
if ( j>=lent ) {
printf("%d\n",i-lent+1);
}
else printf("-1\n");
}
int main()
{
while ( ~scanf("%s %s",s,t) ) {
getpre();
kmp();
}
return 0;
}