longest common subsequence of two strings(最长公共子序列)

题目描述

Find a longest common subsequence of two strings.

输入描述:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出描述:

For each case, output k – the length of a longest common subsequence in one line.

示例:

abcd
cxbydz

输出:

2


解:

题目意思是每个字符只要是相对顺序就可以,不用必须挨着,示例中字符串2中‘c...d...’就是最长公共子序列。

本题用暴力会超时。

动规:

dp[i][j]存放的是str1前i个字符和str2前j个字符中的最长公共子序列的长度。

如果str1[i]==str2[j]——dp[i][j] = dp[i-1][j-1] + 1;

否则——dp[i][j] = max(dp[i-1][j],dp[i][j-1]);

#include <iostream>
using namespace std;
int main()
{
    int dp[101][101];
    string s1,s2;
    while(cin>>s1>>s2)
    {
        int len1,len2;
        len1 = s1.size();
        len2 = s2.size();
        
        for(int i=0; i<=len1; i++)  //前面说过dp[i][j]的意思,比如dp[len1][len2]是s1
        {
            dp[i][0] = 0;           //前len1-1个字符和s2前len2-1个字符,s1中第len1个字符
        }
        for(int j=0; j<=len2; j++)  //的下标是s1[len-1]
        {
            dp[0][j] = 0;
        }
        for(int i=1; i<=len1; i++)
        {
            for(int j=1; j<=len2; j++)
            {
                if(s1[i-1] != s2[j-1])
                {
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
                }
                else
                    dp[i][j] = dp[i-1][j-1]+1;
            }
        }
        cout<<dp[len1][len2]<<endl;

    }
    return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值