动态规划求最大回文字符串并输出


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);
            }
    } 

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值