lintcode-medium-Longest Common Subsequence

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

Your code should return the length of LCS.

 

Example

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

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

 

 

动态规划:

用一个二维int数组表示A中前i个字符和B中前j个字符的LCS

状态转移:

当A的第i - 1个字符和B的第j - 1个字符相等时,dp[i][j] = dp[i - 1][j - 1] + 1

不相等时,选取dp[i - 1][j]和dp[i][j - 1]中较大的作为dp[i][j]的值

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) {
        // write your code here
        
        if(A == null || A.length() == 0 || B == null || B.length() == 0)
            return 0;
        
        int m = A.length();
        int n = B.length();
        int[][] dp = new int[m + 1][n + 1];
        
        dp[0][0] = 0;
        for(int i = 1; i <= m; i++)
            dp[i][0] = 0;
        
        for(int i = 1; i <= n; i++)
            dp[0][i] = 0;
        
        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] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
        
        return dp[m][n];
    }
}

 

posted @ 2016-03-26 03:08  哥布林工程师  阅读(263)  评论(0编辑  收藏  举报