Given two strings s and T. Find the length of the longest common subsequence of these two strings.
Input:
N=4
M=4
s= "ABCD"
t= "BECD"
Output:
3 ("BCD")
This type of problem is known as the longest common sub-sequence problem (Lcs,longest Common subsequence).
Max (Dp[i][j]+1,dp[i][j+1],dp[i+1][j]) (s=t)
dp[i+1][j+1]=
Max (Dp[i][j+1],dp[i+1][j]) (other)
This recursion can be calculated using O (nm), dp[n][m] is the length of the LCS.
J\i |
0 |
1{B} |
2{e} |
3{C} |
4{D} |
0 |
0 |
0 |
0 |
0 |
0 |
1{a} |
0 |
0 |
0 |
0 |
0 |
2{B} |
0 |
1 |
1 |
1 |
1 |
3{C} |
0 |
1 |
1 |
2 |
2 |
4{D} |
0 |
1 |
1 |
2 |
3 |
1 intn,m;2 CharS[max],t[max];3 intDp[max][max];//DP Array4 5 voidSolve ()6 {7 for(intI=0; i<=n; i++){8 for(intj=0; j<=m; J + +){9 if(s[i]==T[j]) {Tendp[i+1][j+1]=dp[i][j]+1; One } A Else{ -dp[i+1][j+1]=max (dp[i][j+1],dp[i+1][j]); - } the } - } -printf"%d\n", Dp[n][w]); -}
From:<< Challenge Program Design Competition >>
Longest common sub-sequence problem (LCS)