The original title link is here: http://www.lintcode.com/en/problem/longest-common-substring/#
Topic:
Given, strings, find the longest common substring.
Return the length of it.
The characters in
substringShould occur continuously in original string. This was different with
subsequence.
Example
Given A = "ABCD"
, B = "CBCE"
, return 2
. "BC"
Challenge
O (n x m) time and memory.
Exercises
Similar to longest Common subsequence.
Dp. Reference http://www.geeksforgeeks.org/longest-common-substring/
DP[I][J] Represents the length of the str1 of I and str2 longest common substring of length J.
Look at the suffix of two substring.
DP[I][J] = dp[i-1][j-1] + 1 if Str1.charat (i-1) = = Str2.charat (j-1).
DP[I][J] = 0. O.w
Time Complexity:o (m*n). Space:o (m*n).
AC Java:
1 Public classSolution {2 /**3 * @paramA, b:two string.4 * @return: The length of the longest common substring.5 */6 Public intlongestcommonsubstring (String A, String B) {7 if(A = =NULL|| B = =NULL){8 return0;9 }Ten intm =a.length (); One intn =b.length (); A int[] DP =New int[M+1] [N+1]; - intLongest = 0; - for(inti = 1; i<=m; i++){ the for(intj = 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] = 0; - } +Longest =Math.max (Longest, dp[i][j]); A } at } - returnlongest; - } -}
Lintcode Longest Common Substring