# Longest Palindromic Substring


#include<iostream>
#include<string>
using namespace std;
string expand(string a,int l,int r)
{

while(l>=0&&r<a.size())
{

if(a[l]==a[r])
{
l--;
r++;
}
else
break;
}

//cout<<a.substr(l+1,r-l-1)<<endl;
return a.substr(l+1,r-l-1);
}

string longstr(string a)
{
if(a.size()==0)
return " ";
if(a.size()==1)
return a;
int longeststr=1;
string str1,str2,str=a.substr(0,1);

for(int i=0;i<a.size()-1;i++)
{
str1=expand(a,i,i);
if(str1.size()>longeststr)
{
longeststr=str1.size();
str=str1;

}
str2=expand(a,i,i+1);
if(str2.size()>longeststr)
{
longeststr=str1.size();
str=str2;
}
}
return str;
}

void main()
{
string a="abdfdbsdf";
a=longstr(a);
cout<<a;

}

Manacher’s Algorithm解法：


#include<iostream>
#include<vector>
#include<string>
using namespace std;

class Solution
{
public: string para(string a)
{
string result;
if(a.length()<2)
return a;
vector<int>p(a.length()*2+1,0);
result.push_back('#');
for(int i=0;i<a.length();i++)
{
result.push_back(a[i]);
result.push_back('#');
}

int id=0;
int max=0;
for(int i=0;i<2*a.length()+1;i++)
{
if(max>i)
{
if(p[2*id-i]>max-i)
p[i]=max-i;
else
p[i]=p[2*id-i];

}
else
p[i]=0;
while(i-p[i]-1>=0&&i+p[i]+1<2*a.length()+1&&result[i+p[i]+1]==result[i-p[i]-1])
p[i]++;
if(max<p[i]+i)
{
max=p[i]+i;
id=i;
}
}
int maxlen=0;
int maxid=0;
for(int i=0;i<result.length();i++)
{
if(maxlen<p[i])
{
maxlen=p[i];
maxid=i;
}
}
return a.substr((maxid-p[maxid])/2,p[maxid]);
}
};

void main()
{
Solution solution;
string a("1211213214111");
cout<<solution.para(a)<<endl;
}


#### LeetCode(5) Longest Palindromic Substring

2013-11-27 14:00:30

#### 求最长回文子串(Longest Palindromic Substring)

2013-11-22 11:12:03

#### leetcode 5 Longest Palindromic Substring--最长回文字符串

2016-08-29 00:22:17

#### [LeetCode]5 Longest Palindromic Substring(C++，Python实现)

2014-05-23 21:28:36

#### LeetCode5——Longest Palindromic Substring 最易懂的解法

2016-01-22 23:05:18

#### LeetCode 5 Longest Palindromic Substring(C,C++,Python,Java)

2015-05-06 15:38:22

#### 5LongestPalindromicSubstring

2016-09-19 14:34:40

#### Longest Palindromic Substring -- LeetCode

2014-03-10 03:49:51

#### LeetCode Longest Palindromic Substring 最长回文子字符串 两种方法分析解答

2013-11-23 10:27:57

#### [leetcode: Python]5.Longest Palindromic Substring

2017-05-17 10:32:45