http://www.lintcode.com/en/problem/longest-common-substring/
http://www.jiuzhang.com/solutions/longest-common-substring/
- 狀態(tài)定義:dp[i][j] str1 以 i 為尾的所有substring 對應 str2 以 j 為尾的所有 substring 所匹配的最大長度
- 狀態(tài)轉移方程:
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
- 循環(huán)體:雙循環(huán)
- 返回 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;
}