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"
分析
令p[i][j]表示以s[i]开头,s[j]结尾的子串是否为回文串。
若i=j,则p[i][j]=1;
若s[i]!=s[j],则p[i][j]=0;
若s[i]=s[j],
若i+1=j,则p[i][j]=1;
否则,p[i][j]=p[i+1][j-1];
找出满足p[i][j=1的]j-i的最大值
代码
#include <iostream>
#include<string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
int n=s.size();
bool p[n][n];
for (int i = n-1; i >= 0; --i)
for (int j= i; j < n; ++j) {
if (i==j) p[i][j]=1;
else if (s[i]!=s[j]) p[i][j]=0;
else if (s[i]==s[j]) {
if (i+1==j)
p[i][j]=1;
else
p[i][j]=p[i+1][j-1];
}
}
int length=0;
int begin=0,end=0;
for (int i = 0; i < n; ++i)
for (int j =i; j < n; ++j) {
if (p[i][j] && j-i+1>length) {
length=j-i+1;
begin=i;
end=j;
}
}
return s.substr(begin,end-begin+1);
}
};