My problem-solving ideas:
Generate a dynamic planning table, which is a matrix DP of size m*n (M and n are two string lengths respectively);
DP[I][J] Process:
1. Matrix The first column is dp[0~m-1][0], for a certain position (i,0), if str1[i]==str2[0], to dp[i][0]=1,. otherwise dp[i][0]=0;
2. The first line of the matrix is dp[0][0~n-1], for a position (0,J), if STR1[0]==STR2[J], to dp[0][j]=1,. otherwise dp[i][0]=0;
3. The rest of the positions are calculated from left to right, top to bottom, and the value of dp[i][j] may only be in two cases:
A. If STR1[I]!=STR2[J], it is impossible to make the last character of the common substring str1[i] and str2[j], so that dp[i][j]=0;
B. If str1[i]==str2[j], description str1[i] and str2[j] can be used as the last character of the common substring, dp[i][j]=dp[i-1][j-1]+1;
After generating the dynamic planning table, the largest number in the table is the length of the common substring
Here is the specific code:
#include <iostream>
#include <string>
using namespace Std;
int dp[8][8] = {0};//the size of the two-dimensional matrix is defined by itself, guaranteeing the ability to tolerate the string.
void Initdp (char *str1, char *str2)
{
int len1 = strlen (STR1);
int len2 = strlen (STR2);
for (int i = 0; i < len1; i++)
{
if (str1[i] = = Str2[0])
{
Dp[i][0] = 1;
}
}
for (int j = 1; j < Len2; J + +)
{
if (str2[j] = = Str1[0])
{
DP[0][J] = 1;
}
}
for (int i = 1; i < len1; i++)
{
for (int j = 1; j < Len2; J + +)
{
if (str1[i] = = Str2[j])
{
DP[I][J] = dp[i-1][j-1] + 1;
}
}
}
}
void Maxchar (char *str1, char *str2)
{
int len1 = strlen (STR1);
int len2 = strlen (STR2);
int max = 0;
int end = 0;
for (int i = 0; i < len1; i++)
{
for (int j = 0; J < Len2; J + +)
{
if (Dp[i][j]>max)
{
max = Dp[i][j];
end = i;
}
}
}
for (int i = end-max+1; I <= end; ++i)
{
printf ("%c", Str1[i]);
}
printf ("\ n");
}
int main ()
{
Char *str1 = "AB123CD";
Char *str2 = "DB1234CG";
INITDP (str1, str2);
Maxchar (str1, str2);
return 0;
}
If there's a better way for a great God, please tell the niche, thank you.
The longest common substring problem