[Problem] Given two strings A and B, respectively, of length m and n, they are required to find the longest common substring, and returns its length. For example:
A = "the HelloWorld"
B = "Loop"
the A and B longest common substring "lo", the returned length is 2.
[Idea] longest common substring of the longest common subsequence is different from the problem due to the continuous, but not necessarily sequence substring continuous. When dp [i] in one sub-sequence [j] of non-decreasing, thus finally returns the largest common subsequence, returns dp [n] [m]. In the biggest problem substring, dp [i] [j] may be smaller than dp [i-1] [j -1], it is necessary to save the updated maximum value of a res.
Popular considered, looking at the two sub-strings, assuming a [i] == b [j ] , then i and j away from the back, would have been updated RES increases, once they are not equal, then the DP [i ] [j] is cleared , find the next repeat substring. So the recursive formula:
Wherein dp [i] [0] = 0, dp [0] [j] = 0;
class LongestSubstring { public: int findLongest(string A, int n, string B, int m) { if(n == 0 || m == 0) return 0; int rs = 0; int dp[n + 1][m + 1]; for(int i = 0 ; i <= n; i++)//初始状态 dp[i][0] = 0; for(int i = 0; i <= m; i++) dp[0][i] = 0; for(int i = 1; i <= n; i++) for(int j = 1; j<= m; j++) { if(A[i - 1] == B[j - 1]) { dp[i][j] = dp[i -1][j - 1] + 1; rs Max = (RS, DP [I] [J]); // every time recording the maximum update } the else // not equal DP [I] [J] = 0 ; } return RS; // returned as the result RS } };