Longest Palindromic Substring


题目分析

1. 这题是要求找最长回文子序列,比较普通的做法是直接枚举中点,然后向两侧扩展,这样是O(N^2)的算法。


2. 不过可以用 Manacher 算法在O(N)以内找出来,参考了这篇博客文章的题目,感觉讲得很详细了, 还有配图, 就不额外进行分析了。https://segmentfault.com/a/1190000003914228


class Solution {
public:
	string longestPalindrome(string s) {
		int len = s.length();
		string str;
		str.push_back('#');
		for (int i = 0; i < len; i++) {
			str.push_back(s[i]);
			str.push_back('#');
		}
		len = str.length();
		vector<int> p(len, 0);
		int maxRight = 0;
		int center = 0;
		int i = 0, j = 0;
		int max = -1, maxindex = 0;
		for (int i = 0; i < len; i++) {
			if (i < maxRight) {
				p[i] = (i + p[center - (i - center)] <= maxRight) ? p[center - (i - center)] : maxRight - i;
				j = i + p[i];
			}
			else j = i;
			while (i - (j - i) - 1 >= 0 && j + 1 < len && str[j + 1] == str[i - (j - i) - 1])
				j++;
			p[i] = j - i;
			if (j > maxRight) {
				maxRight = j;
				center = i;
			}
			if (p[i] > max) {
				max = p[i];
				maxindex = i;
			}
		}
		string result = "";
		for (int k = maxindex - max; k <= maxindex + max; k++) {
			if (str[k] != '#') result.push_back(str[k]);
		}
		return result;
	}
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值