• Dynamic Programming


    实现如下:

    public static void main(String[] args) {
            
            String squence1 = "ABCBDAB";
            String squence2 = "BDCABC";
            
            int len1 = squence1.length(), len2 = squence2.length();
            if (len1 <= 0 || len2 <= 0) {
                System.out.println("empty squence!");    
                return;
            }
            int[][] allCommonSubLen = new int[len1+1][len2+1];
            //print all sub-squences
            String subSquence = "";
            //初始化i=0, j=0
            for (int i = 0; i < len1; i++) {
                allCommonSubLen[i][0] = 0;
            }
            for (int j = 0; j < len2; j++) {
                allCommonSubLen[0][j] = 0;
            }
            //迭代关系
            for (int i = 1; i <= len1; i++) {
                for (int j = 1; j <= len2; j++) {
                    char c1 = squence1.charAt(i-1);
                    char c2 = squence2.charAt(j-1);
                    if (c1 == c2) {
                        //subSquence += c1;
                        allCommonSubLen[i][j] = allCommonSubLen[i-1][j-1] + 1;
                        //System.out.println("i="+i+" ; j="+j+" ; subSquence="+subSquence);
                    } else {
                        allCommonSubLen[i][j] = Math.max(allCommonSubLen[i-1][j], allCommonSubLen[i][j-1]);
                        if (allCommonSubLen[i][j] == allCommonSubLen[i-1][j]) {
                            //subSquence += c2;
                            //System.out.println("i="+i+" ; j="+j+" ; subSquence="+subSquence);
                        } else {
                            //subSquence += c1;
                            //System.out.println("i="+i+" ; j="+j+" ; subSquence="+subSquence);
                        }
                    }                
                }
            }
            //System.out.println(allCommonSubLen[len1][len2]);
        }
    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    MVC6 发布IIS
    Spring-Spring Bean后置处理器
    Java中重载和重写
    Java基础
    Python高级教程-多重继承
    Spring Bean声明周期
    Spring Bean作用域
    Spring-ApplicationContext容器
    Spring-BeanFactory容器
    Spring-Spring IoC容器
  • 原文地址:https://www.cnblogs.com/hello-yz/p/4666203.html
Copyright © 2020-2023  润新知