【leetcode】5. 最长回文子串

我们就可以在 O(n^2)O(n2) 的时间内解决这个问题。

我们观察到回文中心的两侧互为镜像。因此,回文可以从它的中心展开,并且只有 (2n - 1 )个这样的中心。

你可能会问,为什么会是 2n - 12n−1 个,而不是 nn 个中心?原因在于所含字母数为偶数的回文的中心可以处于两字母之间(例如 “abba”的中心在两个‘b’ 之间)。

示例代码:

#include<iostream>
#include<string>
using namespace std;

//求字符串以start为开始时的最长回文串
int expandAroundCenter(string s, int start, int end)
{
	while (start >= 0 && end < s.length() && (s.at(start) == s.at(end)))
	{
		start--;
		end++;
	}
	//因为start--和end++后此时的值已经不是回文字符.
	//完整式子为(end-1)-(start+1)+1
	return end - start -1;
}

string longestPalindrome(string s)
{
	//定义最长回文子字符串的起始和终止位置
	int start = 0, end = 0;
	for (int i = 0;i < s.length();i++)
	{
		int iLength = expandAroundCenter(s, i, i);
		int isspaceLength = expandAroundCenter(s, i, i + 1);
		//选最大长度
		int maxLength = iLength > isspaceLength ? iLength : isspaceLength;
		//更新start和end;
		if (maxLength > end - start + 1)
		{
			//偶数长度
			if (maxLength % 2 == 0)
			{
				start = (i + 1) - maxLength / 2;
				end = i + maxLength / 2;
			}
			else
			{
				start = i - maxLength / 2;
				end = i + maxLength / 2;
			}
		}
	}
	//返回回文字符串
	return s.substr(start, end - start + 1);

}

int main()
{
	string s1 = "babad";
	string s2 = "cbbd";
	cout << longestPalindrome(s1) << endl;
	cout << longestPalindrome(s2) << endl;


	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值