f[i][j]表示的是以第i个结尾和第j个结尾
class Solution { public: /* * @param A: A string * @param B: A string * @return: the length of the longest common substring. */ int longestCommonSubstring(string &A, string &B) { // write your code here int length1 = A.length(); int length2 = B.length(); vector<vector<int> > result(length1+1,vector<int>(length2+1)); for(int i = 0;i <= length1;i++) result[i][0] = 0; for(int j = 0;j <= length2;j++) result[0][j] = 0; for(int i = 1;i <= length1;i++){ for(int j = 1;j <= length2;j++){ if(A[i-1] == B[j-1]) result[i][j] = result[i-1][j-1] + 1; else{ result[i][j] = 0; } } } int max = 0; for(int i = 1;i <= length1;i++){ for(int j = 1;j <= length2;j++){ if(result[i][j] > max) max = result[i][j]; } } return max; } };