求两个字符串的最长公共子序列(LCS)

求两个字符串的最长公共子序列(Longest common subsequence)

Given two sequences.Find the length of the longest common subsequence(LCS)

Note: A subsequence is different from a substring ,for the former need NOT be consecutive of the original sequence.For example ,for “CHINA” and “CAHNI” ,the longest common subsequence is “CHN” ,and the longth of it is 2.

这道题目是比较典型的动态规划问题,笔者也是新手,为了加深印象,特意花了几张图来加深印象。先看源代码,再看图,加深印象。

/*Author:Chauncy
date:2019年12月10日*/
#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str1,str2;
    cin>>str1;
    cin>>str2;
    int m,n;
    m=str1.length();
    n=str2.length();
    int LCS[m+1][n+1];
    for(int i=0;i<m+1;i++)
        LCS[i][0]=0;
    for(int j=0;j<n+1;j++)
        LCS[0][j]=0;
    for(int i=1;i<=m;i++)
        for(int j=1;j<=n;j++)
        {
        if(str1[i-1]==str2[j-1])
            LCS[i][j]=LCS[i-1][j-1]+1;
        else
            LCS[i][j]=max(LCS[i-1][j],LCS[i][j-1]);
        }
    cout<<LCS[m][n];
    return 0;
}
首先把二维数组的第一行和第一列初始化为0

在这里插入图片描述

遇到相同的,按公式计算当前格子的值。

在这里插入图片描述
按行进行
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了28 篇原创文章 · 获赞 1 · 访问量 619

猜你喜欢

转载自blog.csdn.net/qq_44384577/article/details/103483519