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 Similar Problems
Have you met this question in a real interview?
Yes
No
算法转自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;
}