2 Sequences DP - Longest Common Substring

http://www.lintcode.com/en/problem/longest-common-substring/
http://www.jiuzhang.com/solutions/longest-common-substring/

  • 状态定义:dp[i][j] str1 以 i 为尾的所有substring 对应 str2 以 j 为尾的所有 substring 所匹配的最大长度
  • 状态转移方程:
dp[i][j] = 0 if str1[i - 1] != str2[j - 1]
dp[i][j] = dp[i - 1][j - 1] + 1 if str1[i - 1] == str2[j - 1] 
  • 初始化:
dp[0][j] = 0
dp[i][0] = 0
  • 循环体:双循环
  • 返回 target:max(dp[i][j])

From 九章:

Longest Common Substring
state: f[i][j]表示前i个字符配上前j个字符的LCS‘的长度 (一定以第i个和第j个结尾的LCS’)
function: f[i][j] = f[i-1][j-1] + 1 // a[i] == b[j] = 0 // a[i] != b[j]
intialize: f[i][0] = 0 f[0][j] = 0
answer: MAX(f[0..a.length()][0..b.length()])

public int longestCommonSubstring(String A, String B) {
    // state: f[i][j] is the length of the longest lcs
    // ended with A[i - 1] & B[j - 1] in A[0..i-1] & B[0..j-1]
    int n = A.length();
    int m = B.length();
    int[][] f = new int[n + 1][m + 1];
    
    // initialize: f[i][j] is 0 by default
    
    // function: f[i][j] = f[i - 1][j - 1] + 1 or 0
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (A.charAt(i - 1) == B.charAt(j - 1)) {
                f[i][j] = f[i - 1][j - 1] + 1;
            } else {
                f[i][j] = 0;
            }
        }
    }
    
    // answer: max{f[i][j]}
    int max = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            max = Math.max(max, f[i][j]);
        }
    }
    
    return max;
}

你可能感兴趣的:(2 Sequences DP - Longest Common Substring)