[编程题] 最长公共子串
对于两个字符串,请设计一个时间复杂度为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 str1, int n, string str2, int m) {
// write code here
int length1 = str1.size() ;
int length2 = str2.size() ;
int result = 0 ;
vector<vector<int>> vec( length1 + 1, vector<int>( length2 + 1, 0 ) ) ;
for ( int i = 0; i <= length1; ++ i ) {
for ( int j = 0; j <= length2; ++ j ) {
if ( i == 0 || j == 0 ) {
vec[i][j] = 0 ;
} else if ( str1[i - 1] == str2[j - 1] ) {
vec[i][j] = vec[i - 1][j - 1] + 1 ;
result = result > vec[i][j] ? result : vec[i][j] ;
} else {
vec[i][j] = 0 ;
}
}
}
return result ;
}
};
第二次做:
class LongestSubstring {
public:
int findLongest(string str1, int n, string str2, int m) {
// write code here
vector<vector<int>> vec( str1.size() + 1, vector<int>( str2.size() + 1, 0 ) ) ;
int result = 0 ;
for ( int i = 0; i <= str1.size(); ++ i ) {
for ( int j = 0; j <= str2.size(); ++ j ) {
if ( i == 0 || j == 0 ) vec[i][j] = 0 ;
else if ( str1[i - 1] == str2[j - 1] ) {
vec[i][j] = vec[i - 1][j - 1] + 1 ;
result = result > vec[i][j] ? result : vec[i][j] ;
}
else vec[i][j] = 0 ;
}
}
return result ;
}
};