和經典DP最長公共子串(不要求字符連續)不同,最長公共子字符串要求字符是連續的
class LongestSubstring {
public:
int findLongest(string A, int n, string B, int m) {
//f[i][j] represent the longest common substring starting with A[i] and B[j]
vector<vector<int>> f(n+1, vector<int>(m+1, 0));
//maxlen is the overall max common substring length, starting anywhere
int maxlen = 0;
//dp
for(int i = n-1; i > -1; --i){
for(int j = m-1; j > -1; --j){
if(A[i] != B[j]){
//no such common substring ended with A[i] and B[j]
//f[i][j] remain 0 as initialized
}
else{
//common substring starts with A[i] and B[j]
f[i][j] = f[i+1][j+1] + 1;
maxlen = max(maxlen, f[i][j]);
}
}
}
return maxlen;
}
};