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;
}