class Solution {
public:
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
vector<vector<int> > DP(A.size()+1, vector<int>(B.size()+1, 0));
int ret = 0;
for(int i=0;i<A.size();i++)
for(int j=0;j<B.size();j++) {
int x = i + 1;
int y = j + 1;
if(A[i]==B[j]) {
DP[x][y] = DP[x-1][y-1] + 1;
}else {
DP[x][y] = 0;
}
ret = max(ret, DP[x][y]);
}
return ret;
}
};
子串和子序列差别:子序列可以不连续,子串必须连续。