对于两个字符串,请设计一个时间复杂度为O(m*n)的算法(这里的m和n为两串的长度),求出两串的最长公共子串的长度。这里的最长公共子串的定义为两个序列U1,U2,..Un和V1,V2,...Vn,其中Ui + 1 == Ui+1,Vi + 1 == Vi+1,同时Ui == Vi。
给定两个字符串A和B,同时给定两串的长度n和m。
测试样例:
"1AB2345CD",9,"12345EF",7
返回:4
对于两个字符串,请设计一个时间复杂度为O(m*n)的算法(这里的m和n为两串的长度),求出两串的最长公共子串的长度。这里的最长公共子串的定义为两个序列U1,U2,..Un和V1,V2,...Vn,其中Ui + 1 == Ui+1,Vi + 1 == Vi+1,同时Ui == Vi。
给定两个字符串A和B,同时给定两串的长度n和m。
"1AB2345CD",9,"12345EF",7
返回:4
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 started 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; } };