Longest Common Subsequence(最长公共子序列)

http://www.lintcode.com/zh-cn/problem/longest-common-subsequence/

public class Solution {
    /*
     * @param A: A string
     * @param B: A string
     * @return: The length of longest common subsequence of A and B
     */
    public int longestCommonSubsequence(String A, String B) {
        // write your code here
//        用i来表示A的取了i-1个元素,j表示B取了j-1个元素。
        int[][] dp = new int[A.length() + 1][B.length() + 1];
        for (int i = 1; i < dp.length; i++) {
            for (int j = 1; j < dp[0].length; j++) {
                if (A.charAt(i - 1) == B.charAt(j - 1)) {
//                    相等说是比A取i-2位和B取j-2位的多了1
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
//                     不等说明,这一位不起作用,所以它的值就是A少取一位或者B少取一位中的大的那个
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[dp.length - 1][dp[0].length - 1];
    }
}

你可能感兴趣的:(Longest Common Subsequence(最长公共子序列))