回文是一个正读和反读都相同的字符串,例如,“aba” 是回文,而“abc” 不是。
使用动态规划解决的实现思路:一旦在一个回文串的两端,对称地加上相同的元素,那么新生成的字符串仍然是一个回文串
public class Question_05 {
public static String longestPalindrome(String s) {
char[] ch = s.toCharArray();
//字符串的长度
int length = s.length();
int[][] dp = new int[length][length];
//初始化dp数组,当i==j时表示字符串中只有1个字符,此时肯定是回文字符串
//dp[i][j]=1表示字符串中从i到j之间(即ch[i]和ch[j]之间的包括ch[i]和ch[j])的字符串为回文子串
for (int i=0;i<length;i++){
for (int j=0;j<length;j++){
if (i==j){
dp[i][j]=1;
}else {
dp[i][j]=0;
}
}
}
//设置初始最大长度的头和尾的指针下标
int maxIndex = 1;
int begin = 0;
//如果输入的字符串为"",则直接输出·
if(length==0){
return "";
}
for (int j=0;j<length;j++){
for (int i=0;i<j;i++){
//如果ch[i]!=ch[j],则不用执行任何操作
// if (ch[i]!=ch[j]){
// continue;
// }
//如果ch[i]=ch[j]且两者是相邻的,则他们两个是回文子串
if (ch[i]==ch[j]&&i+1==j){
//设置i,j之间为回文子串
dp[i][j]=1;
if (j+1-i>maxIndex-begin){
maxIndex=j+1;
begin=i;
}
}
//如果ch[i]=ch[j]但两者不相邻的,则要判断他们两者之间(除开ch[i],ch[j])是不是回文子串
if (ch[i]==ch[j]&&i+1!=j&&dp[i+1][j-1]==1){
dp[i][j]=1;
if (j+1-i>maxIndex-begin){
maxIndex=j+1;
begin=i;
}
}
}
}
return s.substring(begin,maxIndex);
}
public static void main(String[] args) {
System.out.println(longestPalindrome("cbbd"));
}
}