首页 > 试题广场 >

Coincidence

[编程题]Coincidence
  • 热度指数:11336 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
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.
示例1

输入

abcd
cxbydz

输出

2
不懂 最长公共子序列 LCS 的可以看看这个视频  【[轻松掌握动态规划]5.最长公共子序列 LCS】 https://www.bilibili.com/video/BV1ey4y1d7oD/?share_source=copy_web&vd_source=04c6684fa67d8e2ecc979a1d59aac249
#include <stdio.h>
#include<string.h>
#define MAX 100

int main() {
    char s1[MAX], s2[MAX];
    int dp[MAX][MAX];
    scanf("%s", s1);
    scanf("%s", s2);
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    memset(dp, 0, sizeof(dp));
    for (int i = 1; i <= len1; i++) {
        for (int j = 1; j <= len2; j++) {
            if (s1[i - 1] == s2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
            else dp[i][j] = (dp[i][j - 1] - dp[i - 1][j] > 0) ? dp[i][j - 1] : dp[i - 1][j];
        }
    }

    printf("%d", dp[len1][len2]);



    return 0;
}



发表于 2025-03-04 21:48:24 回复(0)
//用一个二维数组dp[i][j],表示p[0]~p1[j-1]与p2[0]~p2[i-1]的最长公共子序列长度
int max(int a,int b)
{
    if(a>b)
        return a;
    else
        return b;
}
int main()
{
    char p1[100],p2[100];
    int dp[101][101];
    scanf("%s",p1);
    scanf("%s",p2);
    int len1,len2,i,j;
    len1=strlen(p1);
    len2=strlen(p2);  
    for(i=0;i<=len2;i++)
        dp[i][0]=0;
    for(i=0;i<=len1;i++)
        dp[0][i]=0;
    for(i=1;i<=len2;i++)
    {
        for(j=1;j<=len1;j++)
        {
            if(p1[j-1]==p2[i-1])
            {
                dp[i][j]=dp[i-1][j-1]+1;
            }
            else
            {
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        }
    }
    printf("%d",dp[len2][len1]);
    return 0;
}
发表于 2023-03-02 22:59:09 回复(0)