参考大神讲解的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;
}