Lintcode - Longest common subsequence

来源:互联网 发布:梦幻西游手游数据互通 编辑:程序博客网 时间:2024/05/10 20:41

Given two strings, find the longest comment subsequence (LCS).

Your code should return the length of LCS.

样例

For "ABCD" and "EDCA", the LCS is "A" (or D or C), return 1

For "ABCD" and "EACB", the LCS is "AC", return 2

2d: 一维矩阵应该做不了,因为d[i+1][j+1] 与 d[i][j+1] d[i+1][j] d[i][j]都有关

    public int longestCommonSubsequence(String A, String B) {        int[][] d = new int[A.length()+1][B.length()+1];        for (int i = 0; i < A.length(); i++) {            for (int j = 0; j < B.length(); j++) {                if (A.charAt(i) == B.charAt(j)) {                    d[i+1][j+1] = d[i][j]+1;                } else {                    d[i+1][j+1] = Math.max(d[i][j+1], d[i+1][j]);                }            }        }        return d[A.length()][B.length()];    }


0 0
原创粉丝点击