2021.9.10学习记录(基本算法)对称子字符串的最大长度(习题)

对称子字符串的最大长度

输入一个字符串,输出该字符串中对称的子字符串的最大长度。比如输入字符串“google”,由于该字符串里最长的对称子字符串是“goog”,因此输出4。


#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;


//char s[] = "google";

//判断一个字符串是否是对称的
bool IsSymmetricalString(char* pstart ,char* pend)
{
	//两个指针不能为空
	//头指针不能大于尾指针
	if (pstart == NULL || pend == NULL || pstart > pend)
		return false;

	//头指针小于尾指针时判断两位指针的值是否相等
	while (pstart < pend)
	{
		if (*pstart != *pend)
			return false;
		else
		{
			//头指针指向下一个,类似于s[0++]
			pstart++;
			//尾指针指向上一个,类似于s[len--]
			pend--;
		}
	}
	return true;

}


//求最大对称子串的长度
//从内向外比较
//时间复杂度O(n²)
int MaxStrIntoOut(char* pstring)
{
	int maxlength = 1;

	char* pchar = pstring + 1;//pchar=pstring地址-1的位置
	while (*pchar != '\0')
	{
		char* pfirst = pchar - 1;//pchar地址-1的位置
		char* psecond = pchar + 1;//pchar地址+1的位置

		//
		while (pfirst > pstring && psecond < &pstring[strlen(pstring) - 1] && *pfirst == *psecond)
		{
			pfirst--;
			psecond++;
		}

		int templen = psecond - pfirst + 1;
		if (templen > maxlength)
			maxlength = templen;


		pfirst = pchar - 1;
		psecond = pchar;
		
		while (pfirst > pstring && psecond < &pstring[strlen(pstring) - 1] && *pfirst == *psecond)
		{
			pfirst--;
			psecond++;
		}

		templen = psecond - pfirst + 1;
		if (templen > maxlength)
		{
			maxlength = templen;
		}
		pchar++;
	}
	return maxlength;
}


//从头遍历字符串
//时间复杂度O(n³)
int MaxStrOnetoEnd(char* pstring)
{
	if (pstring == NULL)
		return 0;

	int maxlen = 1;

	int len = strlen(pstring);
	char* pfirst = pstring;
	while (pfirst < &pstring[len - 1])
	{
		char* psecond = pfirst + 1;
		while (psecond <= &pstring[len - 1])
		{
			if (IsSymmetricalString(pfirst, psecond))
			{
				int templen = psecond - pfirst + 1;
				if (templen > maxlen)
				{
					maxlen = templen;
				}
			}
			psecond++;
		}
		pfirst++;
	}
	return maxlen;

}

void main()
{
	cout << "请输入字符串!" << endl;
	char* s = new char[1000];
	cin >> s;

	cout << "对称字符串的最大长度是:" << endl;
	cout << MaxStrOnetoEnd(s) << endl;

	delete[] s;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值