使用动态规划算法求两个字符串的最长公共子串

参考大神讲解的dp的链接,这个讲解dp的链接比较好懂,大家可以收藏起来,哈哈!

 

编写函数,获取两段字符串的最长公共子串的长度 - CSDN博客  https://blog.csdn.net/qq_36828558/article/details/78147946

 

下面不多说,直接上代码。

 

// vivo-找到两个字符串中的最长公共子串.cpp
/*
找出两个字符串中最大公共子字符串
如"abccade","dgcadde"的最大子串为"cad"
*/

/*
分析思路:  
使用动态规划算法
参考自csdn博客https://blog.csdn.net/qq_36828558/article/details/78147946
*/
#include "pch.h"
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
int **getdp(char str1[], char str2[]);
int findLargestSizeCommonString(string str1, string str2);
int main()
{
    string str1;
    string str2;
    while (cin >> str1)
    {
        cin >> str2;
        cout << findLargestSizeCommonString(str1, str2) << endl;
    }
    system("pause");
    return 0;
}

//获取dp矩阵的函数
//重点在于如何返回一个二维数组
int **getdp(const char *str1, const char *str2)
{
    int **dp;
    dp = (int **)malloc(strlen(str1) * sizeof(int **));
    for (int i = 0; i < strlen(str1); i++)
        dp[i] = (int *)malloc(strlen(str2) * sizeof(int));
    
    //第一列赋值
    for (int i = 0; i < strlen(str1); i++)
    {
        if (str1[i] == str2[0])
            dp[i][0] = 1;
        else
            dp[i][0] = 0;
    }

    //第一行赋值
    for (int j = 0; j < strlen(str2); j++)
    {
        if (str1[0] == str2[j])
            dp[0][j] = 1;
        else
            dp[0][j] = 0;
    }

    //其余位置赋值为左上角加1 
    for(int i = 1; i < strlen(str1); i++)
        for (int j = 1; j < strlen(str2); j++)
        {
            if (str1[i] == str2[j])
                dp[i][j] = dp[i - 1][j - 1] + 1;
        }
    return dp;
}

//发现两个字符串最长的公共子串和其长度的函数
int findLargestSizeCommonString(string str1, string str2)
{
    if (str1 == "" || str2 == "")
        return -1;
    const char *arr1 = str1.c_str();
    const char *arr2 = str2.c_str();
    int **dp = getdp(arr1, arr2);
    int end = 0;
    int maxlen = 0;
    for (int i = 0; i < strlen(arr1); ++i)
    {
        for (int j = 0; j < strlen(arr2); ++j)
        {
            if (dp[i][j] > maxlen)  // 如果所在值大于 maxlen
            {
                end = i;             // end 即为结束子串的位置下标
                maxlen = dp[i][j];         // 更新maxlen 
            }
        }
    }
    cout << str1.substr(end - maxlen + 1, maxlen) << endl;
    return maxlen;
}
 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸡啄米的时光机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值