The original title link is here: http://www.lintcode.com/en/problem/longest-common-subsequence/
Topic:
Given, strings, find the longest common subsequence (LCS).
Your code should return the length of the LCS.
Clarification
What ' s the definition of longest Common subsequence?
- Https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
- Http://baike.baidu.com/view/2020307.htm
Example
For "ABCD"
"EDCA"
and, the LCS is "A"
(or "D"
, "C"
), return 1
.
"ABCD"
for and "EACB"
, the LCS "AC"
is, return 2
.
Exercises
Dp. Reference http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
DP[I][J] Represents the length of the str1 length of I and the length of the str2 LCS of J.
If Str1.charat (i-1) = = Str2.charat (j-1) tail character is the same, dp[i][j] = dp[i-1][j-1]+1.
If different dp[i][j] = Math.max (Dp[i-1][j], dp[i][j-1]).
Example: 1. "Aggtab" and "Gxtxayb". Last characters match for the strings. So length of the LCS can be written as:
L ("Aggtab", "gxtxayb") = 1 + L ("Aggtab", "Gxtxayb")
2. "Abcdgh" and "AEDFHR". Last characters does not match for the strings. So length of the LCS can be written as:
L ("Abcdgh", "aedfhr") = MAX (L ("ABCDG", "AedfhR"), L ("AbcdgH", "AEDFH")).
Time Complexity:o (m*n). Space:o (m*n).
AC Java:
1 Public classSolution {2 /**3 * @paramA, b:two strings.4 * @return: The length of longest common subsequence of A and B.5 */6 Public intlongestcommonsubsequence (String A, String B) {7 if(A = =NULL|| B = =NULL){8 return0;9 }Ten intm =a.length (); One intn =b.length (); A int[] DP =New int[M+1] [N+1]; - for(inti = 1; i<=m; i++){ - for(intj = 1; j<=n; J + +){ the //two end char match, number is dp[i-1][j-1]+1 - if(A.charat (i-1) = = B.charat (j-1)){ -DP[I][J] = dp[i-1][j-1]+1; -}Else{ +DP[I][J] = Math.max (dp[i][j-1],dp[i-1][j]); - } + } A } at returnDp[m][n]; - } -}
Lintcode Longest Common subsequence