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.


O(N^2)的算法。
class Solution {
public:
    string longestPalindrome(string s) {
    	if(s.size() <= 1)
			return s;
		int maxLen = 1;
		int maxMid = 0;
		//odd
		for(int i = 0; i < s.size(); ++i){
			int cnt = 1;
			while(i - cnt >= 0 && i + cnt < s.size() && s.at(i-cnt) == s.at(i+cnt))	++cnt;
			if(cnt > maxLen){
				maxLen = cnt;
				maxMid = i;
			}
		}
		//even
		int maxLLen = 0;
		int maxLeft = 0;
		for(int i = 0; i < s.size(); ++i){
			int cnt = 1;
			while(i - cnt + 1 >= 0 && i + cnt < s.size() && s.at(i-cnt+1) == s.at(i + cnt))	++cnt;
			if((cnt - 1) > maxLLen){
				maxLLen = (cnt-1);
				maxLeft = i;
			}
		}
		stringstream oss;
		if(2*maxLen - 1 > 2*maxLLen)
		{
			for(int i = maxMid - maxLen + 1; i <= maxMid + maxLen - 1; ++i)
				oss << s.at(i);
		}
		else
		{
			for(int i = maxLeft - maxLLen + 1; i <= maxLeft + maxLLen; ++i)
				oss << s.at(i);
		}

		return oss.str();
    }
};

Manacher’s Algorithm: O(N)的动态规划!只用了28ms,上一个方法用了256ms。
参考:
http://www.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
http://www.felix021.com/blog/read.php?2040


class Solution {
public:
    string preProcess(string s){
		int n = s.length();
		stringstream oss;
		oss << '^';
		for(int i = 0; i < n; ++i)
			oss << "#" << s[i];
		oss << '#';
		oss << '$';
		return oss.str();
	}
	
    string longestPalindrome(string s) {
		string T = preProcess(s);
		int n = T.length();
		int *P = new int[n];
		int C = 0, R = 0;
		for(int i = 1; i < n - 1; ++i){
			int i_mirror = 2*C - i;
			P[i] = (R > i)? min(R-i, P[i_mirror]): 0;
			while(T[i+1+P[i]] == T[i-1-P[i]])
				++P[i];
			if(i + P[i] > R){
				C = i;
				R = i + P[i];
			}
		}
		int maxLen = 0;
		int centerIndex = 0;
		for(int i = 1; i < n - 1; ++i){
			if(P[i] > maxLen){
				maxLen = P[i];
				centerIndex = i;
			}
		}
		delete[] P;
		return s.substr((centerIndex - 1 - maxLen)/2, maxLen);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值