# 5. 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.

Example:

``````Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

``````

Example:

``````Input: "cbbd"

Output: "bb"
``````

``````class Solution {
public:
void getLen(string s,int m,int n,int &pos,int &len)
{
while(m>=0 && n<s.length() && s[m]==s[n])
{
--m;
++n;
}
if(n-m-1>len)
{
pos=m+1;
len=n-m-1;
}
}
string longestPalindrome(string s) {
int n=s.length();
int start=0;
int maxlen=1;
for(int i=0;i<n;++i)
{
getLen(s,i,i,start,maxlen);
getLen(s,i,i+1,start,maxlen);
}
return s.substr(start,maxlen);

}
};
``````

Define P[ i, j ] ← true iff the substring Si … Sj is a palindrome, otherwise false.

P[ i, j ] ← ( P[ i+1, j-1 ] and Si = Sj ) ，显然，如果一个子串是回文串，并且如果从它的左右两侧分别向外扩展的一位也相等，那么这个子串就可以从左右两侧分别向外扩展一位。

P[ i, i ] ← true
P[ i, i+1 ] ← ( Si = Si+1 )

``````class Solution {
public:
string longestPalindrome(string s) {
int n=s.length();
int start=0;
int maxlen=1;
bool isPalindrome[1000][1000]={false};
for(int i=0;i<n;++i)
{
isPalindrome[i][i]=true;
}
for(int j=0;j<n-1;++j)
{
if(s[j]==s[j+1])
{
isPalindrome[j][j+1]=true;
start=j;
maxlen=2;
}
}
for(int len=3;len<=n;++len)
{
for(int i=0;i<n-len+1;++i)
{
int j=i+len-1;
if(isPalindrome[i+1][j-1] && s[i]==s[j])
{
isPalindrome[i][j]=true;
start=i;
maxlen=len;
}

}
}
return s.substr(start,maxlen);

}
};
``````