Question:
Returns the longest common string (LCS) for two substrings)
If d (I, j) is set to the length of LCS of A and B, when A [I] = B [j], d (I, j) = d (I-1, j-1) + 1; otherwise d (I, j) = max (d (I-1, j), d (I, J-1)}, time complexity is O (nm ), n and m are the lengths of sequence A and sequence B, respectively.
You can use a scrolling array to optimize the space complexity.
The following section does not describe the use of scrolling arrays.
Optimized version of space without scrolling array ....
#include
#include
const int MAXN=512;char a[MAXN],b[MAXN];int dp[MAXN][MAXN];int main(){while(~scanf(%s%s,a+1,b+1)){memset(dp,0,sizeof(dp));int len_a=strlen(a+1);int len_b=strlen(b+1);for(int i=1;i<=len_a;i++){for(int j=1;j<=len_b;j++){if(a[i] == b[j])dp[i][j]= dp[i-1][j-1]+1;elsedp[i][j]= dp[i][j-1] > dp[i-1][j]? dp[i][j-1] : dp[i-1][j];}}printf(%d,dp[len_a][len_b]);}}
Scroll array optimization space:
Set dp1 to the previous column, and dp2 to the next column.
#include
#include
const int MAXN=512;char a[MAXN],b[MAXN];int dp1[MAXN],dp2[MAXN];int main(){while(~scanf(%s%s,a+1,b+1)){memset(dp1,0,sizeof(dp1));memset(dp2,0,sizeof(dp2));int len_a=strlen(a+1);int len_b=strlen(b+1);for(int i=1;i<=len_a;i++){for(int j=1;j<=len_b;j++){if(a[i] == b[j])dp2[j]= dp1[j-1]+1;elsedp2[j]= dp2[j-1] > dp1[j]? dp2[j-1] : dp1[j]; }memcpy(dp1,dp2,sizeof(dp2));}printf(%d,dp1[len_b]);}}