2015年5月6日星期三

Longest Common Subsequence

Given two strings, find the longest comment subsequence (LCS).
Your code should return the length of LCS.
Example
For "ABCD" and "EDCA", the LCS is "A" (or D or C), return 1
For "ABCD" and "EACB", the LCS is "AC", return 2
state: dp[i][j] 表示前i个字符配上前j个字符的LCS长度(必须包括以i j结尾的字符)
function: dp[i][j] 有两种情况:
               1. charAt(i) = charAt(j) dp[i][j] = dp[i-1][j-1], dp[i][j-1], dp[i-1][j]中最大的一个
               2. charAt(i) != charAt(j) dp[i][j] =dp[i][j-1], dp[i-1][j]中最大的一个 (只有最后一个不同, 可能i字符和j-1相同 或者j和i-1相同)
initial: 二维数组所以dp[i][0] = 0 dp[0][j] = 0
return: dp[m][n]

public class Solution {
    /**
     * @param A, B: Two strings.
     * @return: The length of longest common subsequence of A and B.
     */
    public int longestCommonSubsequence(String A, String B) {
        if (A == null || B == null) {
            return 0;
        }
        int m = A.length();
        int n = B.length();
        int[][] dp = new int[m+1][n+1];
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (A.charAt(i - 1) == B.charAt(j - 1)) {
                    dp[i][j] = Math.max(dp[i-1][j-1] + 1, Math.max(dp[i][j-1], dp[i-1][j]));
                } else {
                    dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]);
                }
            }
        }
        return dp[m][n];
    }
}

没有评论:

发表评论