leetcode练习5(最大长度的回文字符串)

题目:给定一个字符串,输出其中长度最大的回文字符串。
题解(1):遍历字符串,检查以字符串的某个(某相邻两个)字符为中心,向字符串左右展开,是否满足回文字符串的要求

class solution
{
private:
	string str;
public:
	solution(string strs) :str(strs) {};
	void count() {
		int count = 0;    //记录最大回文字符串的长度
		int record = 0;    //记录回文字符串的起始位置
		for (int i = 0;i < str.length()-2;i++)
		{
			int counts = 0;
			int left = 0, right = 0;   //左指针,右指针,用于拓宽回文字符串的长度

			if (str[i] == str[i + 2])  //若回文字符串有中心单字符
			{
				counts = 3;
				left = i - 1;
				right = i + 3;
				while (left >= 0 && right < str.length())
				{
					if (str[left] == str[right])
					{
						counts += 2;
						left -= 1;
						right += 1;
					}
					else {
						
						break;
					}
				}
			}
			else if (str[i] == str[i + 1])  //若回文字符串无中心单字符
			{
				counts = 2;
				left = i - 1;
				right = i + 2;
				while (left >= 0 && right < str.length())
				{
					if (str[left] == str[right])
					{
						counts += 2;
						left -= 1;
						right += 1;
					}
					
					else {
						
						
						break;
					}

				}
			}
			if (count < counts)    //记录当前长度最大的回文字符串
			{
				record = left + 1;
				count = counts;
			}
		

		}
		string res;
		res = str.substr(record, count);
		cout << res;
	}
};

题解(2):遍历字符串中每一个子串,判断字串是否为回文字符串,在执行判断的过程中运用了动态规划的思想

class solution
{
private:
	string str;
	int result = 0;
	int length = 0;
public:
	solution(string strs) :str(strs) {};
	void count() {
		vector<vector<bool>>res(str.length(), vector<bool>(str.length(), false));
		for (int i = 0;i < str.length();i++)
		{
			for (int start = 0;start + i < str.length();start++)
			{
				int end = 0;
				end = start + i;
				//若end=start,则一定是回文字符串
			    if (i == 0)
				{
					res[start][end] = true;
				}
				//若子字符串只有两个字符,只需判断这两个字符是否相等
				else if (i == 1)
				{
					res[start][end] = (str[start] == str[end] )? true:false;
					
				}
				//判断是否满足子字符串的首字符等于尾字符,以及去首尾后的字符串是否是回文字符串,若满足,则为回文字符串
				else {
					if (str[start] == str[end] && res[start + 1][end - 1] == true && end - start >= 2)
					{
						res[start][end] = true;

					}
				}
				if (res[start][end] == true&&length < end - start + 1)
				{
					length = end - start + 1;
					
					result = start;
					

				}

			}
			
		}
		string strs;
		strs = str.substr(result, length);
		cout << strs<<endl;
		
		
	}
	};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值