給定一個字符串,查找該字符串中的最大回文子串。
如: "a" 最大回文子串爲 "a" 大小爲1
"aa" 最大回文子串爲"aa" 大小爲2
"aaa" 最大回文子串爲"aaa" 大小爲3
"aba" 最大回文子串爲"aba" 大小爲3
"character" 最大回文子串爲"carac" 大小爲5
該問題是一個動態規劃問題。該問題的最優解,具有最優子結構性質,即該最優解可由子問題的最優解組合而成。
假定對於一個從i到j的字符串s[i,j],具有最優解 (a1,a2,...an)。如果去除a1, an,則最優子結構(a2,....an-1)是 s[i+1, j-1]的最優解。
下面要多考慮了, 迴文串奇偶的問題:
下面只記錄了最大的迴文子串的大小,如果需要輸出迴文子串,需要增加一個備完數組記錄該串。
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
String str = null;
while((str=in.nextLine())!=null){
int [][] tt = new int[str.length()+1][str.length()+1];
char [] s = str.toCharArray();
for(int i = str.length()-1; i >= 0; i--){
for(int j = i; j <= str.length(); j++){
if(j==i) {
tt[i][j] = 0;
continue;
}
if((j-i)==1){
tt[i][j] = 1;
continue;
}
char a = s[i];
char b = s[j - 1];
if(a == b){
tt[i][j] = Math.max(tt[i][j-1] + 1, tt[i+1][j-1] + 2);
} else {
tt[i][j] = Math.max(tt[i][j-1], tt[i+1][j]);
}
}
}
System.out.println(tt[0][str.length()]);
}
}