动态规划 最长公共子串与公共序列长度

动态规划 最长公共子串与公共序列

最长公共子串

//动态规划求最长公共子串
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;

int main()
{
    
    
    string s1, s2;
    cin >> s1 >> s2;

    int len1 = s1.length();
    int len2 = s2.length();
    int b[len1][len2];
    //char c1[len1+1]=s1, c2[len2+1]=s2;


    for( int i=0; i<len1; i++ )
    {
    
    
        for( int j=0; j<len2; j++ )
        {
    
    
            b[i][j] = 0;
        }
    }

    int max = b[0][0];

    for( int i=0; i<len1; i++ )
    {
    
    
        for( int j=0; j<len2; j++ )
        {
    
    
            if( s1[i] == s2[j] )
            {
    
    
                if( i==0 && j==0)
                    b[i][j] = 1;
                else
                    b[i][j] = b[i-1][j-1]+1;
            }

            if( max < b[i][j] )
                max = b[i][j];
        }
    }

    cout << s1 << "与" << s2 << "的最大公共子串长度为:" << max << endl;

    return 0;
}

最长公共序列

//动态规划求最长公共序列
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;

int Max( int a, int b )
{
    
    
    return a>b ? a : b;
}

int main()
{
    
    
    string s1, s2;
    cin >> s1 >> s2;

    int len1 = s1.length();
    int len2 = s2.length();
    int b[len1][len2];


    for( int i=0; i<len1; i++ )
    {
    
    
        for( int j=0; j<len2; j++ )
        {
    
    
            b[i][j] = 0;
        }
    }


    for( int i=0; i<len1; i++ )
    {
    
    
        for( int j=0; j<len2; j++ )
        {
    
    
            if( s1[i] == s2[j] )//相同时,与求公共子串相同
            {
    
    
                if( i==0 || j==0)
                    b[i][j] = 1;
                else
                    b[i][j] = b[i-1][j-1]+1;
            }
            else//不相同时,网格中的值为左方邻居和上方邻居的最大值
            {
    
    
                if( i==0 || j==0)
                    b[i][j] = 0;
                else
                    b[i][j] = Max(b[i-1][j], b[i][j-1]);
            }
            cout << b[i][j] << ' ';
        }
        cout << endl;
    }
    cout << endl;

    cout << s1 << "与" << s2 << "的最大公共序列长度为:" << b[len1-1][len2-1] << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_46161051/article/details/116423766