最大回文串

最近笔试时遇到求取最大回文串的题目,相对来说比较简单。

题目:

所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的,比如:“aba”,"c",对于一个字符串,可以通过删除某些字符而变成回文字符串,如:“cabebaf”,删除‘c’,'e','f'后剩下子串'abba'就是回文字符串。

要求,给定任意一个字符串,字符串最大长度1000,计算出最长的回文字符串长度。

如“cabebaf”的回文串包括"c","aba","abba"等,最长回文"abba"长度为4.

输入:字符串

输出:最大的回文字符串长度

示例:

输入:cabbeaf

输出:4


实现代码如下:

#ifndef _PALINDROME_HPP
#define _PALINDROME_HPP

#include <iostream>
using namespace std;

class palindStr
{
private:
	string pdStr;			//原始字符串
	string maxPdstr;		//最大回文串
	int maxLength;			//最大回文串长度

	void calcMaxPdLength()
	{
		int strLength = pdStr.length();
		int sIndex = 0, eIndex= strLength-1;//起始索引和结束索引
		int pdLength = 0;					//回文串长度
		string lPdstr,rPdstr;				//临时回文串,分别存储左半边和右半边
		
		while (sIndex<eIndex)				//外循环
		{
			while (eIndex>=sIndex)			//内循环
			{
				if (pdStr[sIndex]==pdStr[eIndex])			//比较字符是否相等
				{
					if (sIndex != eIndex)
					{
						pdLength += 2;
						lPdstr.insert(lPdstr.end(), pdStr[sIndex++]);	//构建左半边回文串
						rPdstr.insert(rPdstr.begin(), pdStr[eIndex]);	//构建右半边回文串
					}
					else //如果是相同位置字符则只需做一次加法
					{
						pdLength += 1;
						lPdstr.insert(lPdstr.end(), pdStr[sIndex++]);
					}
				}
				--eIndex;					//末端字符索引递减,指向前一个字符
			}

			++sIndex;						//首字符递增,开始下轮循环
			eIndex = strLength-1;			//重置末端字符索引

			if (maxLength<pdLength)			//是否是最大回文字符串
			{
				maxLength = pdLength;
				maxPdstr.clear();
				maxPdstr = lPdstr + rPdstr;
			}
			
			pdLength = 0;					//所有的容器、标志需清零和重置
			lPdstr.clear();				
			rPdstr.clear();
		}
	}
public:
	palindStr(string str) :pdStr(str),maxLength(1)
	{
		calcMaxPdLength();
	}

	int getMaxPdLength()const { return maxLength; }
	string getMaxPdStr()const{ return maxPdstr; }

	~palindStr(){}

};
#endif //_PALINDROME_HPP

注:如有更好的思路请私信我,谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值