leetcode Longest Palindromic Substring

Longest Palindromic Substring

My Submissions
Total Accepted: 70417  Total Submissions: 338025  Difficulty: Medium

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.

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


算法转自http://www.cnblogs.com/caterpillarofharvard/articles/4245626.html,但是由于本人理解力切佳,所以就在纸上画了画。





代码如下:


// test5LongestPalindromicSubstring.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "string"
#include "vector"

using std::string;
using std::vector;

string longPalindrome(string s)
{
	if (s.size() < 2)
		return s;
	int center=0, right=0;
	int max = 0;
	int j = 0;
	int n = s.size();
	vector<int> len;
	int currentlen = 0;
	len.push_back(1);
	for (int i = 1; i < n; i++)
	{
		if (i <= right)
		{
			j = 2 * center - i;
			if (len[j] + i < center)
			{
				currentlen = len[j];
				len.push_back(currentlen);
				continue;
			}
		}
		currentlen = 0;
		int l = i, r = i;
		while (l >= 0 && r<n && s[l] == s[r])//注意此处,最后一个判定条件必须放到后面的后面,否则将会出错。
		{
			currentlen++;
			r++;
			l--;
		}
		len.push_back(currentlen);
		if (currentlen > max)
		{
			center = i;
			right = center + currentlen - 1;
			max = currentlen;
		}
	}

	string result = "";
	int left = center - max + 1;
	if (left % 2 == 0)
		left++;
	while (left<right)
	{
		result += s[left];
		left+=2;
	}
	return result;

}

string longestPalindrome(string s)
{
	if (s.size() < 2)
		return s;
	string temp = "#";
	for (int i = 0; i < s.size(); i++)
	{
		temp += s[i];
		temp += '#';
	}
	return longPalindrome(temp);
}

int _tmain(int argc, _TCHAR* argv[])
{
	string s = longestPalindrome("aaaba");
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值