Given two strings, find the longest common subsequence (LCS). Your code should return the length of LCS. Example

Example 1:
    Input:  "ABCD" and "EDCA"
    Output:  1
    Explanation:
    LCS is 'A' or  'D' or 'C'
Example 2:
    Input: "ABCD" and "EACB"
    Output:  2
    Explanation: 
    LCS is "AC"
dp[i][j]表示string A中前i个字符串和string B中前j个字符串的lcs的长度。
若A的第i个字符与B的第j个字符相同,那么dp[i][j]等于A的前i-1个字符串与B的前j-1个字符串的lcs的长度+1,即dp[i-1][j-1]+1;
若A的第i个字符与B的第j个字符不同,那么dp[i][j]要么等于A的前i个字符串与B的前j-1个字符串的lcs的长度,
要么等于A的前i-1个字符串与B的前j个字符串的lcs的长度(看哪个更大)。
public class Solution {
    public int longestCommonSubsequence(String A, String B) {
        int[][] dp = new int[A.length() + 1][B.length() + 1];
        for(int i = 1; i < A.length() + 1; i++) {
            for(int j = 1; j < B.length() + 1; 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[A.length()][B.length()];
    }
}

results matching ""

    No results matching ""