最长公共子序列

来源:互联网 发布:手机网络渗透 编辑:程序博客网 时间:2024/05/01 19:00
public class Solution {    public static void main(String[] args) {        String s1 = "ABCDE";        String s2 = "ABdcE";        // 生成包含最长公共子序列长度的矩阵dp        int[][] lcssArray = getdp(s1, s2);        // 遍历最长公共子序列长度矩阵dp        System.out.println("最长公共子序列长度的dp矩阵为:");        Solution.traverseArray(lcssArray);      }    /**     * 生成最长公共子序列长度矩阵dp     *      * @param str1     * @param str2     * @return     */    public static int[][] getdp(String str1, String str2) {        char[] chr1 = str1.toCharArray();        char[] chr2 = str2.toCharArray();        // 创建dp数组, dp[i][j]表示最大公共子序列的长度        int[][] dp = new int[chr1.length][chr2.length];        // 初始化dp数组首地址        dp[0][0] = chr1[0] == chr2[0] ? 1 : 0;        // 处理第一列        for(int i = 1; i < chr1.length; i++) {            dp[i][0] = Math.max(dp[i - 1][0], chr1[i] == chr2[0] ? 1 : 0);        }        // 处理第一行        for(int j = 1; j < chr2.length; j++) {            dp[0][j] = Math.max(dp[0][j - 1], chr2[j] == chr1[0] ? 1 : 0);        }        // 其他行列元素的处理        for(int i = 1; i < chr1.length; i++) {            for(int j = 1; j < chr2.length; j++) {                dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);                if(chr1[i] == chr2[j]) dp[i][j] = Math.max(dp[i][j], dp[i-1][j-1] + 1);            }        }        return dp;    }    public static void traverseArray(int array[][]) {        for(int i = 0; i < array.length; i++) {            for(int j = 0; j < array[0].length; j++) {                System.out.print(" " + array[i][j]);            }            System.out.println();        }    }}