对于两个字符串,请设计一个时间复杂度为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
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int findLCS(string A, int n, string B, int m)
{
vector<vector<int> > f( n+1, vector<int>( m+1, 0));
int maxlen = 0;
for( int i = n-1; i>-1; --i)
{
for(int j = m-1; j>-1; --j)
{
if(A[i] != B[j])
{}
else
{
f[i][j] = f[i+1][j+1] + 1;
maxlen = max( maxlen, f[i][j]);
}
}
}
return maxlen;
}
int main()
{
string s1="abab";
int m=4;
string t1="baba";
int n=4;
int res;
res = findLCS(s1,m,t1,n);
cout<< res <<endl;
return 0;
}
a b c e f
a 3 0 0 0 0 0
b 0 2 0 0 0 0
c 0 0 1 0 0 0
d 0 0 0 0 0 0
0 0 0 0 0 0
这种思路也很浅显易懂,但是是java语言写的,没有转换成相应的C、C++
首先,所求是最大子串,不是子序列,说明是连续的。
LS问题,用动态规划思想,把大问题分解成若干小问题,用矩阵记录状态结果:
若s是两个字符串s1和s2敏感词有的字符,s1中s左侧的字符串为s1’,s2中s左侧的字符串为s2’,那么截止到s为止,LS(s1, s2) = LS(s1’, s2’)+1,用矩阵记录结果,例如bab和c aba,矩阵如下:
我们用全局变量max记录最大值,同时可以记录最后一次+1时的行号或列号,结合max可以推算出子串。
public class LongestSubstring {
public int findLongest(String A, int n, String B, int m) {
if(n == 0 || m == 0){
return 0;
}
//初始化状态矩阵
int[][] matrix = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
matrix[i][j] = 0;
}
}
int max = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(A.charAt(i) == B.charAt(j)){
if(i == 0 || j == 0){
matrix[i][j] = 1;
}else{
matrix[i][j] = matrix[i-1][j-1] + 1;
}
max = (max > matrix[i][j] ? max : matrix[i][j]);
}
}
}
return max;
}
}