Topic Links:
Title Analysis: Assume that two strings are labeled STR1 and STR2, respectively. Establishes a two-dimensional table dp,dp[i][j] represents the number of the longest common subsequence of the first I character of the str1 and the first J characters of the str2, traversing all elements of str1 and str2, if str1[i] = Str2[j], then dp[i][j] = dp[i-1][j-1 ] + 1; otherwise dp[i][j] = max (dp[i-1][j],dp[i][j-1]). To prevent the array from crossing out, add a row and column to the top and right of the DP, assigning a value of 0. The calculation process is shown in the following table, where the red number represents the need to add 1.
|
|
A |
D |
F |
S |
D |
|
0 |
0 |
0 |
0 |
0 |
0 |
A |
0 |
1 |
1 |
1 |
1 |
1 |
S |
0 |
1 |
1 |
1 |
2 |
2 |
D |
0 |
1 |
2 |
2 |
2 |
3 |
F |
0 |
1 |
2 |
3 |
3 |
3 |
Reference code:
#include <stdio.h> #include <string.h> int dp[1001][1001]; char str1[1001]; Char str2[1001
];
inline int max (const int A, const int b) {return a > b a:b;}
int main () {int n,t;
int i,j;
int nlen1,nlen2;
scanf ("%d", &t);
GetChar ();
while (t--) {gets (STR1);
Gets (STR2);
NLen1 = strlen (STR1);
NLen2 = strlen (STR2);
Memset (Dp,0,sizeof (DP)); for (i = 1; I <= nLen1; ++i) {for (j = 1; j <= NLen2; ++j) {if (str1[i-1] = = Str2[j-1]) dp[i][j]
= Dp[i-1][j-1] + 1;
else dp[i][j] = max (Dp[i-1][j], dp[i][j-1]);
}} printf ("%d\n", Dp[nlen1][nlen2]); }
}