---
title: "[KMP-next数组特性]HDU 2594 Simpsons’ Hidden Talents"
author: "Coco_young"
date: "2012-06-27T17:37:00Z"
tags: []
slug: "kmp-next-hdu-2594-simpsons-hidden-talents"
draft: false
lastmod: "2013-02-03T02:37:18Z"
id: 1786439
url: "https://coco-young.iteye.com/blog/1786439"
---

如果不了解next数组前缀后缀特性的请看我以前写的一道题：[http://blog.csdn.net/airarts\_/article/details/7686441](http://blog.csdn.net/airarts_/article/details/7686441)

传送门：[http://acm.hdu.edu.cn/showproblem.php?pid=2594](http://acm.hdu.edu.cn/showproblem.php?pid=2594)

题目大意：给定字符串s1,s2要求出s1的最长前缀，同时还是s2的最长后缀，输出该字符串和其长度.

解题思路：利用前缀后缀特性，把两个字符串接起来，按照前面那题的方法，来求前缀后缀子串，注意其终止条件的变化，这里前缀后缀子串的长度必须小于s1,s2长度的最小值。

代码：

```
#include<iostream>
using namespace std;
const int MAXN = 111111;
int next[MAXN],Min;
char s[MAXN],t[MAXN];
void makenext(){
    int M = strlen(s),i=0,j=-1;next[0]=-1;
    while(i<=M){
        if(s[i]==s[j]||j==-1)next[++i]=++j;
        else j = next[j];
    }
}
void solve(){
    int i = strlen(s);
    i = next[i];
    while(i>Min&&i>0){
        i = next[i];
    }
    s[i] = 0;
    if(i!=0)
    printf("%s %d\n",s,i);
    else
    printf("%d\n",i);
}
int main(){
    while(scanf("%s%s",s,t)!=EOF){
        Min = min(strlen(s),strlen(t));
        strcat(s,t);
        makenext();
        solve();
    }
    return 0;
}
```