题目
给定一个字符串,找到字符串中最长的回文子串
例如:
abcdcbd
最长回文子串为:bcdcb
分析思路
动态规划思想,假设找到了最长的回文子串,那么去掉两头的字母,依然是回文子串数。
先找长度为1的回文数,然后判断该回文子串的两端增加字符后是否是回文子串,如果是则留下来,如果不是则舍弃。
记录开始位置、结束位置是否是回文子串
需要考虑边界条件
代码
package org.example.palindrome;
public class Palindrome {
public static String palindrome(char[] s){
int len = s.length;
boolean[][] palindromeLen = new boolean[len][len];
String ans = "";
//循环回文字符串长度
for (int paLen = 0; paLen < len ; paLen++) {
//开始位置
for (int i = 0; i < len; i++) {
//结束位置
int j = i+paLen;
if(j>=len)
break;
if(paLen ==0){
palindromeLen[i][j] = true;
}else if(paLen==1){
//如果相邻字母相同,则也是回文数
palindromeLen[i][j] = s[i]==s[j];
}else {
//如果短字符串是回文数,并且两端字母相同,则也是回文数
palindromeLen[i][j] = palindromeLen[i+1][j-1]&&s[i]==s[j];
}
if(palindromeLen[i][j]&& paLen+1>ans.length())
ans = new String(s).substring(i,j+1);
}
}
return ans;
}
public static void main(String[] args) {
String s = "aba";
System.out.println("最长为:"+palindrome(s.toCharArray()));
String s2 = "aa";
System.out.println("最长为:"+palindrome(s2.toCharArray()));
String s3 = "adfacafs";
System.out.println("最长为:"+palindrome(s3.toCharArray()));
}
}