leetcode - Longest Palindromic Substring

题目:

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, and there exists one unique longest palindromic substring.


分析:

运用manacher算法,实现O(n)时间复杂度。参考这里

class Solution {
public:
	string longestPalindrome(string s) {
		if (s.empty())
			return s;
		if (s.size() <= 2)
		{
			if (s[0] == s[s.size() - 1])
				return s;
			else
				return s.substr(0, 1);
		}

		int size = s.size();
		string str(2 * size + 1, '#');
		for (int i = 0, j = 1; i<size; ++i, j += 2)
		{
			str[j] = s[i];
		}

		size = str.size();
		vector<int> f(size, 0);
		f[1] = 2;
		//max_len是str最大半径,max_center是取值max_len时的下标
		int max_len = 2, max_center = 1;
		//cur_right是当前半径向右延伸所能到达的最大下标,center是取值cur_right时的下标
		int cur_right = 2, center = 1;
		for (int i = 2; i <= size - 3; ++i)
		{
			if (i>cur_right)
			{
				int r = 1;
				while (i - r >= 0 && i + r<size && str[i - r] == str[i + r])
					++r;
				f[i] = r;
			}
			else
			{
				int i2 = center * 2 - i, i2_left = i2 - f[i2] + 1, center_left = center - f[center] + 1;
				if (i2_left<center_left)
				{
					f[i] = cur_right - i + 1;
				}
				else if (i2_left == center_left)
				{
					int r = cur_right - i + 1;
					while (i - r >= 0 && i + r<size && str[i - r] == str[i + r])
						++r;
					f[i] = r;
				}
				else
				{
					f[i] = f[i2];
				}

			}
			//更新max_len和max_center
			if (f[i]>max_len)
			{
				max_len = f[i];
				max_center = i;
			}
			//更新cur_right和center
			if (i + f[i] - 1>cur_right)
			{
				cur_right = i + f[i] - 1;
				center = i;
			}

		}

		string res = str.substr(max_center - max_len + 1, 2 * max_len - 1);
		//删除字符 '#'
		res.erase(remove(res.begin(), res.end(), '#'), res.end());
		return res;

	}
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值