Coincidence(最长公共子序列)

本文介绍了一种使用动态规划解决两个字符串最长公共子序列问题的方法,并提供了完整的C语言实现代码。
题目描述: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.
样例输入:abcdcxbydz
样例输出:2提示:本题题意很明显就是求两个字符串的最长公共子序列,两个字符串S1和S2,第S1[x] 与 S2[y]的最长公共子序列d[x][y],如果S1[x] == S2[y],那么很明显,d[x][y] = d[x - 1][y - 1] + 1;如果S1[x] != S2[y] 那么d[x][y] = max(d[x][y - 1], d[x - 1][y]);
 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 char s1[101];
 5 char s2[101];
 6 int d[101][101];
 7 int main() {
 8     int len1, len2;
 9     while(~scanf("%s%s", s1, s2)){
10         len1 = strlen(s1);
11         len2 = strlen(s2);
12         for(int i = 0; i <= len1; i++)
13             d[i][0] = 0;
14         for(int i = 0; i <= len2; i++)
15             d[0][i] = 0;
16         for(int i = 1; i <= len1; i++){
17             for(int j = 1; j <= len2;j++){
18                 d[i][j] = 0;
19                 if(s1[i - 1] == s2[j - 1])
20                     d[i][j] = d[i - 1][j - 1] + 1;
21                 else
22                     d[i][j] = d[i - 1][j] > d[i][j - 1] ? d[i - 1][j] : d[i][j - 1];
23             }
24         }
25             printf("%d\n",d[len1][len2]);
26     }
27 }

 

转载于:https://www.cnblogs.com/babyron/archive/2013/02/21/2920894.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值