Longest common sub-sequence problem (LCS)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.