小白进阶之路-HDU - 2594

题意:给你两个字符串s1,s2,让你寻找最长s1前缀和s2后缀的匹配长度,若长度大于0,且输出最长匹配s1前缀。

 

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 100;
int nxt[maxn];

/*
 * 题目思路:把s2拼接在s1后,问题变成了拼接后字符串s的最后前缀后缀匹配长度,但因为有可能
            长度超过s1,s2的长度,所以限制一下条件。求最长前缀和后缀的匹配长度也就是KMP
            中求NEXT数组的方法。
 */
 
/*
 * 感想:初学KMP,对于一些概念的理解还不是很深入,这题我思考了很久,用前后缀比对,MLE,
 * 用子串函数,TLE。。。细细想来就明白了。还要多加训练。
 */

void GetNextArray(char *s)
{
    int len = strlen(s);
    nxt[0] = -1;nxt[1] = 0;
    int i = 1,cn = 0;
    while(i < len){
        if(s[i] == s[cn]){
            nxt[++i] = ++cn;
        }else if(cn > 0){
            cn = nxt[cn];
        }else{
            nxt[++i] = 0;
        }
    }
}

int main()
{
    char s1[maxn],s2[maxn];
    while(~scanf("%s%s",s1,s2)){
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        strcat(s1,s2);
        GetNextArray(s1);
        int ans = nxt[strlen(s1)];
        while(ans > len1 || ans > len2){
            ans = nxt[ans];
        }
        if(ans <= 0){
            printf("0\n");
        }else{
            s1[ans] = 0; // 添加终止符号,得到最长匹配长度的前缀。
            printf("%s %d\n",s1,ans);
        }
    }
    return 0;
}

 

posted @ 2020-05-29 23:54  Wise_4  阅读(142)  评论(0编辑  收藏  举报