九度OJ 1042 Coincidence -- 动态规划(最长公共子序列)

本文介绍了一个解决最长公共子序列问题的算法实现。通过动态规划的方法,该程序能够找出两个字符串之间的最长公共子序列,并输出其长度。文章提供了一个完整的C语言程序示例,用于处理长度不超过100的字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:http://ac.jobdu.com/problem.php?pid=1042

题目描述:

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
#include <stdio.h>
#include <string.h>
 
#define MAX 101
 
int main(void){
    char first[MAX], second[MAX];
    int len1, len2;
    int i, j;
    int subseq[2][MAX];
 
    while (scanf ("%s%s", first, second) != EOF){
        len1 = strlen (first);
        len2 = strlen (second);
        for (i=0; i<=len2; ++i)
            subseq[0][i] = 0;
        subseq[1][0] = 0;
        for (i=1; i<=len1; ++i){
            for (j=1; j<=len2; ++j){
                if (first[i-1] == second[j-1])
                    subseq[i%2][j] = subseq[(i-1)%2][j-1] + 1;
                else{
                    subseq[i%2][j] = (subseq[(i-1)%2][j] > subseq[i%2][j-1]) ? subseq[(i-1)%2][j] : subseq[i%2][j-1];
                }
            }
        }
        printf ("%d\n", subseq[len1%2][len2]);
    }
     
    return 0;
}

HDOJ上相似的题目:http://acm.hdu.edu.cn/showproblem.php?pid=1243


参考资料:http://www.cnblogs.com/liyukuneed/archive/2013/05/22/3090597.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值