Coincidence (九度教程第 98 题)
1.题目描述:
Find a longest common subsequence of two strings.
输入:
First and second line of each input case contain two strings of lowercase
character a…z. There are no spaces before, inside or after the strings. Lengths of
strings do not exceed 100.
输出:
For each case, output k – the length of a longest common subsequence in one
line.
样例输入:
abcd
cxbydz
样例输出:
2
来源:
2008 年上海交通大学计算机研究生机试真题
2.基本思路
这个问题我在前面的动态规划专题的文章中有详细的分析,戳此链接
为了不重复描述这里只给出递推方程:
d
p
[
i
,
j
]
=
{
0
,
i=0 or j=0
d
p
[
i
−
1
,
j
−
1
]
+
1
,
i,j>0;xi =yj
max
{
d
p
[
i
−
1
,
j
]
,
d
p
[
i
,
j
−
1
]
}
,
i,j>0;xi !=yj
dp[i,j] = \begin{cases} 0, & \text{i=0 or j=0} \\ dp[i-1,j-1] + 1, & \text{i,j>0;xi =yj}\\ \max\{dp[i-1,j],dp[i,j-1]\}, & \text{i,j>0;xi !=yj} \end{cases}
dp[i,j]=⎩⎪⎨⎪⎧0,dp[i−1,j−1]+1,max{dp[i−1,j],dp[i,j−1]},i=0 or j=0i,j>0;xi =yji,j>0;xi !=yj
dp[i][j],表示字符串1的前i个字符和字符串2的前j个字符对应的最长公共子序列的长度。
3.代码实现
#include <iostream>
#include <string.h>
#define N 101
using namespace std;
char s1[N],s2[N];
int dp[N][N];//动态规划矩阵
int l1,l2;//两字符串的长度
int max(int a,int b){return a>b?a:b;}
int main()
{
while(scanf("%s%s",s1,s2)!=EOF){
l1 = strlen(s1);
l2 = strlen(s2);
for(int i=0;i<=l1;i++){//初始化第0列
dp[i][0] = 0;
}
for(int j=0;j<=l2;j++){//初始化第0行
dp[0][j] = 0;
}
//自左向右,至上向下求解规划矩阵
for(int i=1;i<=l1;i++){
for(int j=1;j<=l2;j++){
if(s1[i-1]==s2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
}
else{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
printf("%d\n",dp[l1][l2]);
}
return 0;
}
/*
样例输入:
abcd
cxbydz
样例输出:
2
*/