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, x ij = 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
我这个代码,同时把那个最长公共子序列输了出来;
/*
子序列:可以不连续
子串:连续
dp[i][j]表示第一个子字符串在第i个字符前且第二个字符串在第j个字符前
dp[i][j] = 0 i=0 || j=0
dp[i-1][j-1]+1 str1[i]==str2[j]
max(dp[i-1][j],dp[i][j-1]) str1[i]!=str2[j]
dp[i][j]记录两个字符串的最长的公共字符子序列有几个字符,也就时最大值
且最后的结果存在dp[strlen(str1)][strlen(str2)]
例如:
0 1 2 3 4 5 6
yi B D C A B A
0 xi 0 0 0 0 0 0 0
1 A 0 0 0 0 1 0 1
2 B 0 1 1 1 1 2 2
3 C 0 1 1 2 2 2 2
4 B 0 1 1 2 2 3 3
5 D 0 1 2 2 2 3 3
6 A 0 1 2 2 3 3 4
7 B 0 1 2 2 3 4 4
*/
#include<stdio.h>
#include<string.h>
#include<stack>
#include<math.h>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
char str1[100];
char str2[100];
str1[0]=str2[0]='0';//把两个字符串的第一个元素都赋值为零
int dp[110][110]={0};
scanf("%s%s",str1+1,str2+1);//从第一个位置开始输入字符串
for(int i=1; i<=strlen(str1)-1; i++)
{
for(int j=1; j<=strlen(str2)-1; j++)
{
if(str1[i]==str2[j])
{
dp[i][j]=dp[i-1][j-1]+1;
}//如果两个字符相等,那么dp就等于上一个对角线的值加1
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
//回溯求lcs:最大公共子序列
int pos1=strlen(str1)-1;
int pos2= strlen(str2)-1;
stack<char> q;
while(pos1>0&&pos2>0)
{
if(str1[pos1]==str2[pos2])
{
q.push(str1[pos1]);
pos1--;pos2--;
}
else if(dp[pos1-1][pos2]>dp[pos1][pos2-1])
pos1--;
else pos2--;
}
while(!q.empty() )
{
printf("%c%c",q.top() ,q.size() ==1?'\n':' ');
q.pop() ;
}
printf("%d\n",dp[strlen(str1)-1][strlen(str2)-1]);
return 0;
}

本文介绍了一种解决最长公共子序列(LCS)问题的方法,并通过一个C语言程序实现了该算法。该程序不仅可以找出两个字符串的最长公共子序列的长度,还能回溯并输出具体的最长公共子序列。
808

被折叠的 条评论
为什么被折叠?



