最长公共子序列(LCS)

一、思想

动态规划最长公共子串思想详解

if(s[i]==s[j])LCS.length++;
else
{

    1.s1去掉s1[i],比较剩余s1和s2
    2.s2去掉s2[j],比较剩余s1和s2
}

二、代码实现

dp[i][j] 表示字符串A以第i个位置 ,字符串B以第j个位置的最长公共子序列的长度
dp[i][j] = dp[i - 1][j - 1] + 1 if a[i] == a[j]

else dp[i][j] == max(dp[i - 1][j] , dp[i][j - 1]);

最大长度就是 dp[n][m] ,n 为A的长度 ,m为B的长度

还原字符串 ,只需要回到 dp[i][j] 刚开始发生改变的地方即可

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
string s1,s2;
int dp[1000][1000];
int len1,len2;

int main()
{
    while(cin>>s1>>s2)
    {
        memset(dp,0,sizeof(dp));
        len1=s1.length();
        len2=s2.length();
        for(int i=0;i<len1;i++)
            for(int j=0;j<len2;j++)
        {
            if(s1[i]==s2[j])dp[i+1][j+1]=dp[i][j]+1;
            else
            {
                dp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1]);
            }
        }
        cout<<dp[len1][len2]<<endl;
    }
    return 0;
}
posted @ 2018-03-14 20:49  Bryce1010  阅读(85)  评论(0编辑  收藏  举报