1. 程式人生 > >動態規劃——最長公共子串

動態規劃——最長公共子串

package com.chao.dynamicProgramming;

public class LCSL {

    //lcsl()方法用來計算最長公共子序列的長度
    public static int  lcsl(int[][] c, int[][]b, String str1, String str2){

        //int[][] c = new int[str1.length()+1][str2.length()+1];//二維陣列存放當前最長子序列的長度
        //int[][] b = new int[str1.length()+1][str2.length()+1];//記錄最優策略來源
//初始化c[][]的第一行和第一列都為0 for(int row = 0; row <= str2.length(); row++) c[0][row] = 0; for(int column = 0; column <= str1.length(); column++) c[column][0] = 0; //初始化b[][]的第一行和第一列都為0 for(int row = 0; row <= str2.length(); row++) b[0
][row] = 0; for(int column = 0; column <= str1.length(); column++) b[column][0] = 0; //計算最長公共子串的長度 for(int i = 1; i <= str1.length(); i++){ for(int j = 1; j <= str2.length(); j++){ if(str1.charAt(i-1) == str2.charAt(j-1)){ c[i][j] = c[i-1
][j-1] + 1; b[i][j] = 1; }else if((str1.charAt(i-1) != str2.charAt(j-1)) && c[i][j-1] >= c[i-1][j]){ c[i][j] = c[i][j-1]; b[i][j] = 2; }else if((str1.charAt(i-1) != str2.charAt(j-1)) && c[i][j-1] < c[i-1][j]){ c[i][j] = c[i-1][j]; b[i][j] = 3; } } } return c[str1.length()][str2.length()]; } //輸出最長的公共子串 public static void printLCS(int i, int j, String str1, int[][] b){ if(i == 0 || j == 0) return; if(b[i][j] == 1){ printLCS(i-1, j-1, str1, b); System.out.println(str1.charAt(i-1)); }else if(b[i][j] == 2){ printLCS(i, j-1, str1, b); }else{ printLCS(i-1, j, str1, b); } } public static void main(String[] args) { String str1 = "BDCABA"; String str2 = "ABCBDAB"; int[][] c = new int[str1.length()+1][str2.length()+1];//二維陣列存放當前最長子序列的長度 int[][] b = new int[str1.length()+1][str2.length()+1];//記錄最優策略來源 System.out.println(lcsl(c, b, str1, str2)); printLCS(str1.length(), str2.length(), str1, b); } }