#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
char s[maxn], s2[maxn];
int book[maxn];
void getnext(char s2[]) {
int i = 0, j = -1;
book[0] = -1;
while(s2[i] != '\0') {
if(j == -1 || s2[i] == s2[j]) {
i++;
j++;
book[i] = j;
} else {
j = book[j];
}
}
}
int KMP() {
int i = 0, j = 0;
int len = strlen(s), len2 = strlen(s2);
while(i < len && j < len2) {
if(j == -1 || s[i] == s2[j]) {
i++;
j++;
} else {
j = book[j];
}
}
if(j >= len2) {
return i - len2 + 1;
} else {
return -1;
}
}
int main() {
while(~scanf(" %s %s", s, s2)) {
getnext(s2);
int ans = KMP();
printf("%d\n", ans);
}
return 0;
}
KMP
最新推荐文章于 2023-01-23 18:57:44 发布