Lintcode: Longest Common Subsequence, Yan Weimin
Given two strings, find the longest comment subsequence (LCS).Your code should return the length of LCS.ExampleFor "ABCD" and "EDCA", the LCS is "A" (or D or C), return 1For "ABCD" and "EACB", the LCS is "AC", return 2
The question says:
Clarification
What's the definition of Longest Common Subsequence?
* (Note that a subsequence is different from a substring, for the terms of the former need not be consecutive terms of the original sequence .) it is a classic computer science problem, the basis of file comparison programs such as diff, and has applications in bioinformatics.
1. D [I] [j] is defined as s1, the first I of s2, and the longest common subsequence of j strings.
2. D [I] [j] When char I = char j, there are three options: D [I-1] [j-1] + 1, D [I] [j-1], D [I-1] [j], obtain the largest
When char I! = Char j, D [I] [j-1], D [I-1] [j] Take a big one (because the last one is different, therefore, it is possible that the last character of S1.
1 public class Solution { 2 /** 3 * @param A, B: Two strings. 4 * @return: The length of longest common subsequence of A and B. 5 */ 6 public int longestCommonSubsequence(String A, String B) { 7 // write your code here 8 int[][] res = new int[A.length()+1][B.length()+1]; 9 for (int i=1; i<=A.length(); i++) {10 for (int j=1; j<=B.length(); j++) {11 res[i][j] = Math.max(A.charAt(i-1)==B.charAt(j-1)? res[i-1][j-1]+1 : res[i-1][j-1], 12 Math.max(res[i-1][j], res[i][j-1]));13 }14 }15 return res[A.length()][B.length()];16 }17 }