题解 | #Common Subsequence#

原题链接

Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = < x1, x2, ..., xm > another sequence Z = < z1, z2, ..., zk > is a subsequence of X if there exists a strictly increasing sequence < i1, i2, ..., ik > of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = < a, b, f, c > is a subsequence of X = < a, b, c, f, b, c > with index sequence < 1, 2, 4, 6 >. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

Input

The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

Output

For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

最长公共子序列:DP

思路:s1[i]与s2[j]是否匹配,dp[i][j]:以s[i]与s[j]为末尾匹配的最长公共序列长度

  • ①是:dp[i][j]=dp[i-1][j-1]+1 都往前一个字符,再匹配
  • ②否:dp[i][j]=max(dp[i-1][j],dp[i][j-1]) s1往前一个字符,再匹配 或者 s2往前一个字符,再匹配
  • 注意s1[0]、s2[0]为哨兵,表示此时匹配长度为0,不进行实际匹配
#include<iostream>
#include<string>
using namespace std;

const int maxn=5001;

string s1,s2;
int dp[maxn][maxn];

void longest(int m1,int m2){
    for(int i=0;i<m1;i++){
        for(int j=0;j<m2;j++){
            if(i==0||j==0)dp[i][j]=0;//有一个字符串匹配位置为0
            else if(s1[i]==s2[j])dp[i][j]=dp[i-1][j-1]+1;
            else{
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        }
    }
}

int main(){
    while(cin>>s1>>s2){
        s1="0"+s1;
        s2="0"+s2;
        int m1=s1.size();
        int m2=s2.size();
        longest(m1,m2);
        printf("%d\n",dp[m1-1][m2-1]);
    }
    return 0;
}

algorithm 文章被收录于专栏

外源题解补充

全部评论
还有其他的思路吗
点赞 回复 分享
发布于 2023-02-12 10:51 山东
感谢大佬的无私分享
点赞 回复 分享
发布于 2023-02-12 10:45 山东

相关推荐

今天 12:11
复旦大学 Java
点赞 评论 收藏
分享
11-03 18:50
门头沟学院 Java
迷茫的大四🐶:问就是马上到,一周五天,6个月以上,全国可飞
点赞 评论 收藏
分享
少年郎as:这不把公司名贴出来那我可要喷你了哦
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务