import java.util.ArrayList;
import java.util.Scanner;
public class dbDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
int len = lenghOfLCS(s, new StringBuffer(s).reverse().toString());
System.out.println(s.length() - len);
scan.close();
}
public static int lenghOfLCS(String s1, String s2) {
char[] ch1 = s1.toCharArray();
char[] ch2 = s2.toCharArray();
int n1 = s1.length();
int n2 = s2.length();
int[][] table = new int[n1][n2];
if (ch1[0] == ch2[0]){
table[0][0] = 1;}
// ch1首字母与ch2比较
for (int i = 1; i < n2; ++i) {
if (ch1[0] == ch2[i]) {
table[i][0] = 1;
} else {
table[i][0] = table[i-1][0];
}
}
// ch2首字母与ch1比较
for (int i = 1; i < n1; ++i) {
if (ch2[0] == ch1[i]) {
table[0][i] = 1;
} else {
table[0][i] = table[0][i-1];
}
}
// ch1与ch2分别比较
for (int i = 1; i < n1; ++i) {
for (int j = 1; j < n2; ++j) {
if (ch1[i] == ch2[j]) {
table[j][i] = table[j - 1][i - 1] + 1;//如果想等,值等于左上角值+1
} else {
table[j][i] = table[j - 1][i] > table[j][i - 1] ? table[j - 1][i]
: table[j][i - 1];//如果不相等,值等于上方或者左边的值
}
}
}
ArrayList array = new ArrayList();
method(ch1,ch2, table, array, n1-1, n2-1);
return table[n1 - 1][n2 - 1];
}
public static void method(char[] ch1,char[] ch2,int[][] table,ArrayList array,int m,int n){
if(n==0||m==0){
if(table[m][n]==1){
array.add(ch1[0]);
}
System.out.println(array);
return;
}
if((table[m][n]==table[m-1][n-1]+1)&&(ch1[n]==ch2[m])){
array.add(ch1[n]);
method(ch1, ch2, table,array,m-1, n-1);
}else if(table[m][n]==table[m][n-1]){
method(ch1, ch2, table,array,m, n-1);
}else{
method(ch1, ch2, table,array,m-1, n);
}
}
}
动态规划求最大回文字符串并输出
最新推荐文章于 2023-03-24 13:24:12 发布