一、题目描述
给定一个串,如ABCDAB,则 - ABCDAB的真前缀有:{ A, AB,ABC, ABCD, ABCDA } - ABCDAB的真后缀有:{ B, AB,DAB, CDAB, BCDAB }
因此,该串的真前缀和真后缀中最长的相等串为AB,我们称之为该串的“最长的真前后缀”。 试实现一个函数string matched_Prefix_Postfix(string str),得到输入串str的最长的真前后缀。若不存在最长的真前后缀则输出empty
二、输入与输出
1.输入
第1行:串的个数 n 第2行到第n+1行:n个字符串
6
a
ab
abc
abcd
abcda
abcdab
2.输出
n个最长的真前后缀,若不存在最长的真前后缀则输出empty。
empty
empty
empty
empty
a
ab
三、参考代码
#include<iostream>
#include<string>
#include<queue>
#include<math.h>
using namespace std;
void matched_Prefix_Postfix(string s) {
int len = s.length();
int flag = 0;
int k = 0;
int s1 = 1;
int s2 = s.length() - 1;
int l = 1;
if (len == 1) cout << "empty" << endl;
else
{
string* str1 = new string[len - 1];
string* str2 = new string[len - 1];
for (int i = 0; i < s.length() - 1; i++) {
str1[i] = s.substr(0, s1);
s1++;
//cout << str1[i] <<"0" << endl;
str2[i] = s.substr(s2, l);
s2--;
l++;
//cout << str2[i]<<"1" << endl;
}
for (int i = 0; i < len - 1; i++) {
if (str1[i] == str2[i]) {
flag = 1;
k = i;
}
}
if (flag == 1) {
cout << str1[k] << endl;
}
else
{
cout << "empty" << endl;
}
}
}
int main()
{
int sum;
cin >> sum;
while (sum--)
{
string s;
cin >> s;
matched_Prefix_Postfix(s);
}
}
/**********************************************************************
Problem: 1073
Language: C++
Result: AC
Time:7 ms
Memory:2228 kb
**********************************************************************/