首页 > 试题广场 >

最长公共子序列(一)

[编程题]最长公共子序列(一)
  • 热度指数:10389 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个字符串 s1 和 s2,长度为 n 和 m  。求两个字符串最长公共子序列的长度。
所谓子序列,指一个字符串删掉部分字符(也可以不删)形成的字符串。例如:字符串 "arcaea" 的子序列有 "ara" 、 "rcaa" 等。但 "car" 、 "aaae" 则不是它的子序列。
所谓 s1 和 s2 的最长公共子序列,即一个最长的字符串,它既是 s1 的子序列,也是 s2 的子序列。
数据范围 : 。保证字符串中的字符只有小写字母。
要求:空间复杂度 O(n),时间复杂度
进阶:空间复杂度 O(n),时间复杂度

输入描述:
第一行输入一个整数 n 和 m ,表示字符串 s1 和 s2 的长度。
接下来第二行和第三行分别输入一个字符串 s1 和 s2。


输出描述:
输出两个字符串的最长公共子序列的长度
示例1

输入

5 6
abcde
bdcaaa

输出

2

说明

最长公共子序列为 "bc" 或 "bd" ,长度为2    
示例2

输入

3 3
abc
xyz

输出

0
#include <stdio.h>

int max(int a,int b){
    return (a>b?a:b);
}

int min(int n,int m,char* a,char* b,int dp[n+1][m+1]){
    for (int i=0; i<=n; i++) {
        dp[i][0]=0;
    }
    for (int j=0; j<=m; j++) {
        dp[0][j]=0;
    }
    for (int i=1; i<=n; i++) {
         for (int j=1; j<=m; j++) {
                if (a[i-1]==b[j-1]) {
                      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]);
                }
        }
    }
    return dp[n][m];
}

int main(){
    int n,m;
    scanf("%d %d",&n,&m);
    char a[n],b[m];
    int dp[n+1][m+1];
    getchar();
    scanf("%s",a);
    getchar();
    scanf("%s",b);
    printf("%d",min(n, m, a, b, dp));
    return 0;
}

发表于 2024-11-30 10:41:13 回复(0)

using System;

using System.Collections.Generic;

public class Program {

public static void Main() {

    string line = System.Console.ReadLine();

    int n = int.Parse(line.Split()[0]);

    int m = int.Parse(line.Split()[1]);

    line = System.Console.ReadLine();

    char[] s1 = line.Split()[0].ToCharArray();

    line = System.Console.ReadLine();

    char[] s2 = line.Split()[0].ToCharArray();

    int[,] dp = new int[n+1,m+1];

    for(int i=1;in;i++){

        for(int j=1;jm;j++){

            if(s1[i-1] == s2[j-1]){

                dp[i,j] = Math.Max(dp[i,j],dp[i-1,j-1]+1);

            }else{

                dp[i,j] = Math.Max(dp[i-1,j],dp[i,j-1]);

            }

        }

    }

    System.Console.WriteLine(dp[n,m]);

}

}

发表于 2024-09-15 11:50:44 回复(0)