问题描述
- 给出两个字符串,求出这样的一个最长的公共子序列的长度:子序列中的每一个字符都能在两个原串中找到,而且每个字符的先后顺序和原串中的先后顺序一致。
- Sample Input
abcfbc abfcab
programming contest
abcd mnp
- Sample Output
4
2
0
问题分析
- 输入两个串s1,2
- 设MaxLen(i,j)表示:s1的左边i个字符形成的字串,与s2左边的j个字符形成的字串的最长公共子序列的长度(i,j从0开始算),MaxLen(i,j)就是本题的“状态”
- 假定len1 = strlen(s1),len2 = strlen(s2)
- 那么题目就是要求MaxLen(len1,len2)
- 显然:MaxLen(n,0) = 0 (n=0…len1),MaxLen(0,n) = 0 (n=0…len2)
- 递推公式:
if(s1[i-1] == s2[j-1])//s1的最左边字符是s1[0]
MaxLen(i,j) = MaxLen(i-1,j-1) + 1;
else
MaxLen(i,j) = Max(MaxLen(i,j-1),MaxLen(i-1,j));
- 时间复杂度
O
(
m
n
)
\Omicron(mn)
O(mn),m,n是两个字串长度
注 : s 1 [ i − 1 ] ! = s 2 [ j − 1 ] 时 , 注:s1[i-1] != s2[j-1]时 , 注:s1[i−1]!=s2[j−1]时,
M a x L e n ( s 1 , s 2 ) 不 会 比 M a x L e n ( s 1 , s 2 j − 1 ) ) 和 M a x L e n ( s 1 i − 1 , s 2 ) 两 者 之 中 任 何 一 个 小 , 也 不 会 比 两 者 都 大 。 MaxLen(s1,s2)不会比MaxLen(s1,s2_{j-1}))和MaxLen(s1_{i-1},s2)两者之中任何一个小,也不会比两者都大。 MaxLen(s1,s2)不会比MaxLen(s1,s2j−1))和MaxLen(s1i−1,s2)两者之中任何一个小,也不会比两者都大。
代码示例:
#include<iostream>
#include<cstring>
using namespace std;
char sz1[1000];
char sz2[1000];
int maxLen[1000][1000];
int main(){
while( cin >> sz1 >> sz2){
int length1 = strlen(sz1);
int length2 = strlen(sz2);
int nTemp;
int i,j;
for(i = 0; i <= length; i++)
maxLen[i][0] = 0;
for(j = 0; j <= length2; j++)
maxLen[0][j] = 0;
for(i = 1; i <= length1; i++)
for(j = 1; j <= length2; j++){
if(sz1[i-1] == sz2[j-1])
maxLen[i][j] = maxLen[i-1][j-1] + 1;
else
maxLen[i][j] = max(maxLen[i][j-1], maxLen[i-1][j]);
}
cout << maxLen[length1][length2] << endl;
}
return 0;
}
运行示例
![](https://img-blog.csdnimg.cn/20200415144705669.png)
注:文中问题及代码参考 MOOC——《程序设计与算法》(北京大学 郭炜)