Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, …, xm > another sequence Z = < z1, z2, …, zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, …, ik > of indices of X such that for all j = 1,2,…,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output
For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
题目大意:
现在有两个字符串,求出其中最长的相同子序列的长度。两个字符中间可以有其他字符
大体思路:
依然是将大问题转化为若干小问题,先确定边界条件:当两个字符串中任意一个字符串长度为零的时候,其最长公共子序列的长度为零。
从右边开始扫,当两个字符串分别在i,j位置出现相同字符时,问题转化为判断为s1的i-1的位置和s2的j-1的位置结束的最长子序列。而总子序列的长度则可以加一。
也就是当s1[i]==s2[j]时的状态转移方程Max(i,j)=Max(i-1.j-1)+1
而当s1[i]!=s2[j]时,方程可推为:Max[i][j]=max{ Max(i-1,j) , Max(i,j-1) }
递归代码:
在POJ上会超时,但比较容易理解,思路比较清晰,就不加注释了。
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char str1[2000],str2[2000];
int maxlen(int i,int j)
{
if(i==0||j==0)
return 0;
if(str1[i-1]==str2[j-1])
return maxlen(i-1,j-1)+1;
else
return max(maxlen(i-1,j),maxlen(i,j-1));
}
int main()
{
while(cin>>str1>>str2)
{
int len1=strlen(str1);
int len2=strlen(str2);
cout<<maxlen(len1,len2)<<endl;
}
return 0;
}
递推代码:
主要思路是将状态抽象化为一个二维数组,记录状态。比较难想。不会T
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int maxlen[2000][2000];
int main()
{
//freopen("in.txt","r",stdin);
char str[4000],str1[2000],str2[2000];
while(cin>>str1>>str2)
{
int len1=strlen(str1);
int len2=strlen(str2);
for(int i=0;i<len1;++i)//将i,j为零的情况进行记录
maxlen[i][0]=0;
for(int j=0;j<len2;++j)
maxlen[0][j]=0;
for(int i=1;i<=len1;++i){
for(int j=1;j<=len2;++j){
if(str1[i-1]==str2[j-1])
maxlen[i][j]=maxlen[i-1][j-1]+1;//思路和递归版没有区别,只不过改为用二维数组记录状态
else
maxlen[i][j]=max(maxlen[i-1][j],maxlen[i][j-1]);
}
}
cout<<maxlen[len1][len2]<<endl;;
}
return 0;
}