最長公共子序列LCS

  1. 最長公共子序列
  2. 動態規劃問題,局部最小單元:兩值是否相等,相等則從對角線上個位置處的數值+1,繼續狀態延續; 不相等則從上下兩個過去的位置找值保持延續,在上下兩個過去位置中保持着以前的最長子序列。

3.對於狀態的理解,保持最佳的,或者延續最佳的。code

public class LongestCommonSubsequence {
    public static int compute(char[] str1, char[] str2) {
        int substringLength1 = str1.length;
        int substringLength2 = str2.length;
        int[][] opt = new int[substringLength1 + 1][substringLength2 + 1];
        for (int i = substringLength1-1; i >= 0; i--) {
            for (int j = substringLength2-1; j >= 0; j--) {
//                System.out.println(i);
//                System.out.println(j);
//                System.out.println("-*-  ");
                if (str1[i] == str2[j]) {
                    opt[i][j] = opt[i + 1][j + 1] + 1;
                } else {
                    opt[i][j] = Math.max(opt[i + 1][j], opt[i][j + 1]);
                }
            }
        }

        return opt[0][0];
    }
    public static int compute(String str1,String str2){
        return compute(str1.toCharArray(),str2.toCharArray());
    }
    public static void main(String[] args){
        String a1="abcd";
        String a2="bcead";
        int l1=compute(a1,a2);
        System.out.println(l1);
    }
}
相關文章
相關標籤/搜索