您的位置:首页 > 其它

HDU - 2594 Simpsons’ Hidden Talents(KMP)

2015-10-26 22:53 381 查看
题目大意:问你前缀和后缀相等的最长长度

解题思路:KMP的裸题了,next数组的应用

#include <cstdio>
#include <cstring>
const int N = 50010;
char s1
, s2
;
int len1, len2;
int next
;

void getFail() {
len1 = strlen(s1);
len2 = strlen(s2);

int i = 0, j = -1;
next[0] = -1;
while (i < len1) {
if (j == -1 || s1[j] == s1[i]) {
i++; j++;
next[i] = j;
}
else j = next[j];
}
}

void solve() {
int i = 0, j = 0;
while (i < len2) {
if (j == -1 || s1[j] == s2[i]) {
i++; j++;
if (i == len2) break;
if (j == len1) j = next[j];
}
else j = next[j];
}
bool flag = false;
for (int i = 0; i < j; i++) {
printf("%c", s1[i]);
flag = true;
}
if (flag) printf(" ");
printf("%d\n", j);
}

int main() {
while (scanf("%s", s1) != EOF) {
scanf("%s", s2);
getFail();
solve();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: