Description
给定两个字符串,请输出这两个字符串的最大公共子序列
输入格式
两行,一行一个字符串(不包括空格,Tab键),长度不超过1000
输出格式
输出最大公共子序列的长度
输入样例
abbca aba
输出样例
3
分析:
LCS(x,y) =
(1) LCS(x - 1,y - 1) + 1 如果Ax = By
(2) max(LCS(x – 1, y) , LCS(x, y – 1)) 如果Ax ≠ By
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int dp[1005][1005];
int main() {
string s1,s2;
cin>>s1>>s2;
int len1=s1.length();
int len2=s2.length();
for(int i=1;i<=len1;++i){
for(int j=1;j<=len2;++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]);
}
}
}
cout<<dp[len1][len2];
return 0;
}