题目描述:
-
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
-
答疑:
- 解题遇到问题?分享解题心得?讨论本题请访问: http://t.jobdu.com/thread-7766-1-1.html
#include <cstdio>
#include <cstring>
#define MAXSIZE 110
using namespace std;
int main(){
char str1[MAXSIZE],str2[MAXSIZE];
int dp[MAXSIZE][MAXSIZE];
int len1,len2;
while (scanf("%s",str1)!=EOF){
//input
scanf("%s",str2);
//initiate
len1=strlen(str1);
len2=strlen(str2);
strcpy(str1+1,str1);
strcpy(str2+1,str2);
for (int i=0;i<=len1;i++)
dp[i][0]=0;
for (int j=0;j<=len2;j++)
dp[0][j]=0;
//dp
for (int i=1;i<=len1;i++){
for (int j=1;j<=len2;j++){
if (str1[i]==str2[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1];
}
}
printf("%d\n",dp[len1][len2]);
}
return true;
}