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


一、题目描述

给定一个串,如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
**********************************************************************/


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z1Jxxx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值