#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXN 255
typedef char SString[MAXN + 1];
int next[1 << 8];
void get_nextval(SString t) {
int i = 1, j = 0;
next [1] = 0;
while (i < t[0]) {
if (j == 0 || t[i] == t[j]) {
++i; ++j;
if (t[i] != t[j]) next[i] = j;
else next[i] = next[j];
}
else j = next[j];
}
for (int h = 1; h <= i; ++h) {
printf("%d", next[h]);
}
puts("");
}
int Index_KMP(SString s, SString t) {
get_nextval(t);
int i = 0, j = 1;
while (i <= s[0] && j <= t[0]) {
if (j == 0 || s[i] == t[j]) {++i; ++j;}
else j = next[j];
}
if (j > t[0]) return i - t[0];
else return 0;
}
int main() {
SString s, t;
strcpy(s, " aadabbadada"); strcpy(t, " adabbadada");
s[0] = strlen(s) - 1; t[0] = strlen(t) - 1;
printf("%d\n", Index_KMP(s, t));
return 0;
}
08-07