题意
给出两个序列X和Y,找出X和Y的最大公共子序列长度
input:abcdfbc abfcab
output:4
input:programming contest
output:2
input:abcd mnp
output:0
题解
用dp算法找出最大公共子序列的长度maxlen
#include<bits/stdc++.h>
using namespace std;
const int N = 1001;
char s1[N],s2[N];
int maxlen[N][N];
int dp(int i,int j){
if(maxlen[i][j]>=0) return maxlen[i][j];
if(i==0||j==0) return 0;//字符串空,则maxlen=0
else if(s1[i]==s2[j]) return maxlen[i][j]=dp(i-1,j-1)+1;//找到则递增
else return maxlen[i][j]=max(dp(i,j-1),dp(i-1,j));
}
int main(){
while(scanf("%s %s",s1+1,s2+1)!=EOF){//s+1使下标从1开始
memset(maxlen,-1,sizeof(maxlen));
cout<<dp(strlen(s1+1),strlen(s2+1))<<endl;
}
return 0;
}
abcfbc abfcab
4
programming contest
2
abcd mnp
0