求最长公共子序列的长度



/**
 * longest common subsequence
 * @param s1 string字符串 the string
 * @param s2 string字符串 the string
 * @return string字符串
 */
char* LCS(char* s1, char* s2 ) {
    // write code here
    int len1=strlen(s1);
    int len2=strlen(s2);
    int max=0;
    //设置二维数组dp保存最长公共子序列长度,
    int dp[2000][2000]={0};
    for(int i=0;i<len1;i++)
    {
        for(int j=0;j<len2;j++)
        {
            //s1第i个字符和s2第j个字符相等,dp[i][j]根据dp[i][j]进行累加
            if(s1[i] == s2[j])
            {

                dp[i+1][j+1]=dp[i][j]+1;
                //max记录最长公共子序列的长度
                if(dp[i+1][j+1]>max)
                    max=dp[i+1][j+1];
            }
            //s1第i个字符和s2第j个字符不相等,根据状态转移方程
            else
            {
                dp[i+1][j+1]=(dp[i+1][j]>dp[i][j+1]?dp[i+1][j]:dp[i][j+1]);
            }
        }
    }
    printf("%d",max);
    return NULL;
}



全部评论
感谢大佬的分享,很厉害
点赞 回复 分享
发布于 2022-10-23 19:01 陕西

相关推荐

好难。该水了水了不会做的磨了也不会,直接弃疗提前交了
deep666:纯暴力 100 100 30 100
投递拼多多集团-PDD等公司10个岗位 >
点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务