【题目】
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.
【代码】
class Solution {
public:
string longestPalindrome(string s) {
string str="";
int maxLength=1,left=0,right=0;
int length=s.length();
bool p[length][length];
for(int i=0;i<length;++i){
p[i][i]=true;
}
for(int i=0;i<length;++i){
for(int j=i;j>=0;--j){
if(i==j){
continue;
}
if((s[j]==s[i])&&(p[j+1][i-1]||(i<(j+2)))){
p[j][i]=true;
if((i-j+1)>maxLength){
maxLength=i-j+1;
left=j;
right=i;
}
}
else{
p[j][i]=false;
}
}
}
str=s.substr(left,right-left+1);
return str;
}
};
【总结】
动态规划。