HDU 1159 Common Subsequence(LCS)

本文介绍了一种求解两个字符串最长公共子串的动态规划算法,并提供了完整的C语言实现代码。通过比较字符来更新状态矩阵,最终找到最长公共子串的长度。

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

当s1[s]=s2[t]时,在公共子串末尾加上s1[s]

当s1[s]!=s2[t]时,s1当前长度减1与s2比;s2当前长度减1与s1比

if (s1[s] == s2[t]) {
                dp[s+1][t+1] = dp[s][t] + 1;
            } else {
                dp[s+1][t+1] = max(dp[s][t+1], dp[s+1][t]);
            }



具体如下

#include<stdio.h>
#include<string.h>


char s1[1005], s2[1005];
int dp[1005][1005];
int max(int a, int b) {
    return a>b?a:b;
}

void solve() {
    for (int s = 0; s < strlen(s1); s++) {
        for (int t = 0; t < strlen(s2); t++) {
            if (s1[s] == s2[t]) {
                dp[s+1][t+1] = dp[s][t] + 1;
            } else {
                dp[s+1][t+1] = max(dp[s][t+1], dp[s+1][t]);
            }
        }
    }

    printf("%d\n", dp[strlen(s1)][strlen(s2)]);
}



int main(void)
{
    while (scanf("%s %s", s1, s2) != EOF) {
            memset(dp, 0, sizeof(dp));
            solve();
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值