Longest Common Substring
Given two strings, find the longest common substring.
Return the length of it.
Example Given A = "ABCD", B = "CBCE", return 2.
Note The characters in substring should occur continuously in original string. This is different with subsequence.
解题思路:DP
dp[i][j] means the LCS ended with i and j
Base Cases: If any of the string is null then LCS will be 0.
Check if ith character in one string A is equal to jth character in string B
Case 1: both characters are same
LCS[i][j] = 1 + LCS[i-1][j-1] (add 1 to the result and remove the last character from both the strings and check the result for the smaller string.)
Case 2: both characters are not same.
LCS[i][j] = 0
At the end, traverse the matrix and find the maximum element in it, This will the length of Longest Common Substring.
public int longestCommonSubstring(String A, String B) {
if (A == null || A.length() == 0 || B == null || B.length() == 0) {
return 0;
}
int[][] dp = new int[A.length() + 1][B.length() + 1];
int lcs = 0;
for (int i = 1; i <= A.length(); i++) {
for (int j = 1; j <= B.length(); j++) {
if (A.charAt(i - 1) == B.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = 0;
}
lcs = Math.max(lcs, dp[i][j]);
}
}
return lcs;
}