B (1073) : 串应用- 计算一个串的最长的真前后缀

Description

给定一个串,如ABCDAB,则 - ABCDAB的真前缀有:{ A, AB,ABC, ABCD, ABCDA } - ABCDAB的真后缀有:{ B, AB,DAB, CDAB, BCDAB }

因此,该串的真前缀和真后缀中最长的相等串为AB,我们称之为该串的“最长的真前后缀”。 试实现一个函数string matched_Prefix_Postfix(string str),得到输入串str的最长的真前后缀。若不存在最长的真前后缀则输出empty

Input

第1行:串的个数 n 第2行到第n+1行:n个字符串

Output

n个最长的真前后缀,若不存在最长的真前后缀则输出empty。

Sample

Input

6
a
ab
abc
abcd
abcda
abcdab

Output

empty
empty
empty
empty
a
ab

思路

考察next数组的本质理解,对于一字符串str,next[i]本质就是str[0]~str[i - 1]这个区间内的最长前后缀的长度

代码

#include<iostream>
#include<cstdio>
#include <cassert>
#include<string.h>
using namespace std;
int Next[100];
void KmpNex(string str){
    Next[0] = -1;
    for(int i = 0,j = -1;str[i];)  
        if(j == -1 || str[i] == str[j]) Next[++i] = ++j;
        else j = Next[j];  
}
int main(){
    int t;cin>>t;
    while(t--){
        string str;
        cin>>str;
        KmpNex(str);
        if(Next[str.size()] <= 0) 
            cout<<"empty";
        else 
            for(int i = 0;i < Next[str.size()];i++) 
                cout<<str[i];
        cout<<endl;
    }
    return 0;
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值