zoukankan      html  css  js  c++  java
  • 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]);
        }
    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    Windows上DVWA和sqli-labs部署(Debian&Ubuntu)
    easy -heap
    栈迁移基础
    调试下的plt&got
    Linux 下的文件解压
    GitHub的raw.githubusercontent.com无法链接
    ELF文件认知(二)可重定位目标文件
    自动微信聊天
    MinIE: Open Information Extraction system, GROBID, tet-pdf
    MD5 don't know the problem (Solved)
  • 原文地址:https://www.cnblogs.com/hello-yz/p/4666203.html
Copyright © 2011-2022 走看看