Continuous longest common subsequence LCS

Link above: https://blog.csdn.net/slient_love/article/details/104310092

Continuous longest common subsequence LCS

Title Description

Two input strings s1, s2, s1 and the length of a, s2 length is b, the length of the longest common substring s1 and s2 is c, define common factor d = c / (a ​​+ b), required to obtain d and output the results to two decimal places.

Enter a description:

Two input strings s1, s2, length of not more than 100, separated by a space

Output Description:

Output common factor d, the results of two decimals

Example:

Input:

abcdef acbdefh

Output:

0.23

Two continuous strings having a common subsequence def, c = 3, a = 6, b = 7, so there d = c / (a ​​+ b) = 3/13 = 0.23

Do title ideas:

Solve such common subsequence typical problem-solving approach is to use dynamic programming.

Code shows:
#define MAX 101
#include<iostream>
#include<iomanip>
#include<string.h>
using namespace std;

int dp[MAX][MAX];

int main()
{
    char str1[MAX];
    char str2[MAX];
    cin>>str1>>str2;

    int a=strlen(str1);
    int b=strlen(str2);
    int max_len=0; // 最大长度
    // 初始化序列
    for(int i=0;i<=a;i++)
        dp[i][0]=0;
    for(int j=0;j<=b;j++)
        dp[0][j]=0;
    // 递推动态规划
    for(int i=1;i<=a;i++)
        for(int j=1;j<=b;j++)
        {
            if(str1[i-1]==str2[j-1])
                {
                    dp[i][j]=dp[i-1][j-1]+1;
                    // 更新最大长度
                    if(dp[i][j]>max_len)
                        max_len=dp[i][j];
                }
            else
                dp[i][j]=0;

        }
    int c=max_len;
    float ans=(float)c/(a+b);
    //规格化输出
    cout<<c<<endl;
    cout<<setprecision(2)<<ans<<endl;
    return 0;

}

Reference Links:
https://blog.csdn.net/qq_15034457/article/details/79759810

Released four original articles · won praise 0 · Views 80

Guess you like

Origin blog.csdn.net/slient_love/article/details/104311852