Leetcode 05 最长回文子串 Longest Palindromic Substring

以前只求过最长公共子序列,用动态规划做。这道题的难点在如何判断是不是回文的,其实一旦中心确认了,就只要两边一点一点扩展即可,我分了两种情况,中心为一个字符与中心为两个字符,代码可能有点累赘。

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-palindromic-substring

class Solution {
public:
string longestPalindrome(string s) {
	int len = s.size();
	vector<float> centre1;
	vector<float> centre2;
	for (int i = 1; i < len - 1; i++) {
		if (s[i - 1] == s[i + 1]) { centre1.push_back(i);  }
	}
    for (int i = 1; i < len; i++) {
		if (s[i - 1] == s[i]) { centre2.push_back(((float)2 * i - 1) / 2); }
	}

	if (centre1.size() == 0 && centre2.size() == 0) centre1.push_back(0);
	int cnt = 0, max = 0, begin = 0;
	for (int i = 0; i < centre1.size(); i++) {
		float cent = centre1[i];
		cnt = 1;
		int k = 1;
		while (cent - k >= 0 && cent + k < len && s[cent + k] == s[cent - k]) {
			cnt += 2;
			k++;
		}
		if (cnt > max) { max = cnt; begin = cent - k + 1; }
	}
	for (int j = 0; j < centre2.size(); j++) {
		float cent = centre2[j];
		cout << centre2[j] << endl;
		cnt = 0;
		int k = 0;
		while (cent - 0.5 - k >= 0 && cent + 0.5 + k < len && s[cent + 0.5 + k] == s[cent - 0.5 - k]) {
			cnt += 2;
			k++;
		}
		if (cnt > max) { max = cnt; begin = cent - 0.5 - k + 1; }
	}
	string ans = s.substr(begin, max);
	return ans;

}
};

执行用时 :36 ms, 在所有 cpp 提交中击败了78.20%的用户

内存消耗 :9.4 MB, 在所有 cpp 提交中击败了75.08%的用户

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值